No need to explicitly create short objects?

The following code works fine and adds 1 and 2 values ​​to the list, but why? Why don't you need to explicitly create Short objects? for example: list.add(new Short(1));

 List<Short> list = new ArrayList(); list.add((short)1); list.add((short)2); System.out.println(list); 
+6
source share
2 answers

This is called autoboxing . This is a function that automatically converts primitives to the corresponding type of object. It has been present since Java 1.5.

The opposite of autoboxing is called autounboxing, but beware of a NullPointerException

+13
source

This is called auto-boxing.

Note that it will still create true Short objects automatically, and they occupy 16 bytes on your heap, the same as an Integer object. Only eigenvalues ​​of Short occupy only 2 bytes (but cannot be placed in java.util.collections ).

In many situations

 list.put((short) 12345); list.put((short) 12345); 

in fact, it will even create two such objects, i.e. 32 bytes plus the memory occupied by the list object. Pointers stored in the list already occupy 4-8 bytes each.

If you have only a few instances, everything is in order. If you have several millions, this can greatly affect performance due to memory management and usage. With raw shorts, you can usually walk 10 times before becoming slow or running out of memory.

+1
source

Source: https://habr.com/ru/post/915221/


All Articles