What is .intValue() in Java?

前端 未结 8 1423
暗喜
暗喜 2020-12-08 14:01

What is the difference between them?

l is an arraylist of Integer type.

version 1:

int[] a = new int[l.size()];
for (in         


        
8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 14:44

    Consider this example:

    Integer i = new Integer(10);
    Integer j = new Integer(10);
    if (!(i == j)) {
        System.out.println("Surprise, doesn't match!");
    }
    if (i.intValue() == j.intValue()) {
        System.out.println("Cool, matches now!");
    }
    

    which prints

    Surprise, doesn't match!
    Cool, matches now!
    

    That proves that intValue() is of great relevance. More so because Java does not allow to store primitive types directly into the containers, and very often we need to compare the values stored in them. For example:

    oneStack.peek() == anotherStack.peek() 
    

    doesn't work the way we usually expects it to work, while the below statement does the job, much like a workaround:

    oneStack.peek().intValue() == anotherStack.peek().intValue()
    

提交回复
热议问题