Differences and limitations between int [] and Integer [] [duplicate]

-17

Keeping in mind that both int[] e Integer[] are objects according to the Java documentation :

  

An object is a class instance or an array.

And that Integer is the class (type of reference) that encapsulates Immutable way in value int (primitive type), I would like to know the differences of its use, its limitations and what advantages and disadvantages it implies.

    
asked by Awes0meM4n 13.03.2017 в 08:42
source

1 answer

-9

The difference between the two fixes is directly and only related to types that contain as stated in the question and can easily be found on the Internet. However this implies and limits some specific operations on each of the arrangements:

Differences with the 'null' type

The int[] fix can never contain null values, depending on the Java documentation about it :

  

The null reference can always be assigned to any reference type

This is demonstrated by the following line of code and its result:

System.out.println(Arrays.toString(new int[2]));
  

out: [0, 0]

In the same way you will never return null , even if you try to assign it a value (Integer)null . The latter will compile but will give you an NPE.

Integer[] if you can assign null values.

Diffs in the heap

Regarding the location, although the arrangements as objects that are going to reside in the heap in both cases, there is a difference.

  • int[] the primitive types int are going to be embedded with the array.
  • Integer[] the reference types Integer will be each in the heap as objects that are and the array will have embedded the reference to each of these objects of the class Integer . The int que encapsula cada Integer 'will be embedded within its corresponding object that encapsulates them, not in the array.

Regarding the memory occupation, Integer occupies approximately twice the corresponding int .

Differences in calculation speed

Calculations on primitive types are faster. However Integer includes optimizations so there are no appreciable differences, but if it is critical code it is better to use int .

Conclusion

As seen above, it is generally better to use int[] whenever possible and leave the use of Integer[] for when necessary: when you need to use values null or uninitialized in the array, or when require an object type Integer[] or Integer in the code as if you need to later add it to a collection.

EDITO (thanks to LuiggiMendoza):

A clear difference of using int[] e Integer[] is when you send objects of these types to a method that uses varargs as void ejemplo(Object ... args) . If you call it ejemplo (new int[] { 1, 2, 3}) Java recognizes it as 1 argument. If you call it ejemplo(1, 2, 3) Java does a boxing of int to Integer and recognizes it as 3 arguments. If you call it as ejemplo(new Integer[] { 1, 2, 3}) Java it recognizes it as 3 arguments of type Integer .

    
answered by 13.03.2017 в 08:42