Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits of IntegerCache while using Integer? [duplicate]

Tags:

java

integer

In Integer class, there is private static class IntegerCache.

What is the use of this class?

What are the benefits of it while using Integer?

like image 402
Prateek Avatar asked Oct 28 '13 11:10

Prateek


1 Answers

Values between -128 and 127 are cached for reuse. This is an example of the flyweight pattern, which minimizes memory usage by reusing immutable objects.


Beyond being an optimization, this behaviour is part of the JLS, so the following may be relied upon:

Integer a = 1;
Integer b = 1;
Integer c = 999;
Integer d = 999;
System.out.println(a == b); // true
System.out.println(c == d); // false
like image 98
Bohemian Avatar answered Sep 28 '22 17:09

Bohemian