What is .intValue() in Java?

前端 未结 8 1366
暗喜
暗喜 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()
    
    0 讨论(0)
  • 2020-12-08 14:45

    It's just a convenience method for getting primitive value from object of Number: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Number.html

    Consider the code:

    Integer integerValue = Integer.valueOf(123);
    float floatValue = integerValue.floatValue();
    

    The last line is a convenient method to do:

    float floatValue = (float)(int)integerValue;
    

    Since any numeric type in Java can be explicitly cast to any other primitive numeric type, Number class implements all these conversions. As usual, some of them don't make much sense:

    Integer integerValue = Integer.valueOf(123);
    int intValue = integerValue.intValue();
    int intValue2 = (int)integerValue;
    int intValue3 = integerValue;
    
    0 讨论(0)
提交回复
热议问题