What is .intValue() in Java?

前端 未结 8 1365
暗喜
暗喜 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:22

    They are exactly the same. As other posters have mentioned, you can put either the Integer object or the int primitive into the array. In the first case, the compiler will automatically convert the Integer object into a primitive. This is called auto-boxing.

    0 讨论(0)
  • 2020-12-08 14:26

    l.get(i); will return Integer and then calling intValue(); on it will return the integer as type int.

    Converting an int to Integer is called boxing.
    Converting an Integer to int is called unboxing
    And so on for conversion between other primitive types and their corresponding Wrapper classes.

    Since java 5, it will automatically do the required conversions for you(autoboxing), so there is no difference in your examples if you are working with Java 5 or later. The only thing you have to look after is if an Integer is null, and you directly assign it to int then it will throw NullPointerException.

    Prior to java 5, the programmer himself had to do boxing/unboxing.

    0 讨论(0)
  • 2020-12-08 14:31

    Java support two types of structures first are primitives, second are Objects.

    Method that you are asking, is used to retrieve value from Object to primitive.

    All java types that represent number extend class Number. This methods are in someway deprecated if you use same primitive and object type since [autoboxing] was implemented in Java 1.5.

    int - primitive

    Integer - object

    Before Java 1.5 we was force to write

    int i = integer.intValue();

    since Java 1.5 we can write

    int i = integer;

    Those methods are also used when we need to change our type from Integer to long

    long l = integer.longValue();

    0 讨论(0)
  • 2020-12-08 14:35

    The Object returned by l.get(i) is an instance of the Integer class.

    intValue() is a instance method of the Integer class that returns a primitive int.

    See Java reference doc... http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#intValue()

    0 讨论(0)
  • 2020-12-08 14:35

    get(i) will return Integer object and will get its value when you call intValue().In first case, automatically auto-unboxing happens.

    0 讨论(0)
  • 2020-12-08 14:44

    As you noticed, intValue is not of much use when you already know you have an Integer. However, this method is not declared in Integer, but in the general Number class. In a situation where all you know is that you have some Number, you'll realize the utility of that method.

    0 讨论(0)
提交回复
热议问题