简体   繁体   中英

Why there is no Integer pool similar to String pool?

When we create String in JAVA.

String s = new String("hello"); 

This s object is created in a Heap. While

String s = "hello";

which is stored in String pool .

Similarly for the Integer class,

Integer i = new Integer(10); // Created in Heap.

or

Integer  ii = 10;  // Where is this created? Why I have never heard of Integer pool?

Because the flyweight design pattern makes no sense for integers in general - they are mostly not used as constants but as mutable values.

There are some predefined Integer values where it makes sense: like ZERO or ONE. Also an Integer is put into the pool if it is used as a constant.

Edit: just realized that the answer in Why does the behavior of the Integer constant pool change at 127? is better.

About Integer:

Better always use

Integer i = Integer.valueOf(42)

An explanation for the why can be found in the Javadoc comment for this method:

This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

About String:

Strings are not only used by programmers (such as you). They are also heavily used by the JVM itself. All declarations are also simple Strings. The compiled byte code is full of them. The String pool can be considered as the JVM's chache mechanism for all those Strings.

A programmer is also able to use this String pool with the String.intern() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM