What is .intValue() in Java?

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

提交回复
热议问题