-3

java.lang.Integer has an internal cache (IntegerCache) that optimizes access to numbers between -128 to 127. The question is why only between these numbers? Why not -256 to 255?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Alexandre Santos
  • 8,170
  • 10
  • 42
  • 64
  • Why do you think your range is better? – Boris the Spider May 05 '14 at 19:08
  • 4
    If they chose these numbers, you would ask why not -512 to 511. They had to make a good compromise, and chose these numbers. – JB Nizet May 05 '14 at 19:08
  • Not really. Different than the hash code (31), -128 to 127 is completely arbitrary. Are there any proofs (math) that -128 to 127 is better? They also say is it so comply with JLS. But the question remains as why this specific range. Also, if the range is so important then why allow it to be modified? – Alexandre Santos May 05 '14 at 19:15
  • 3
    @AlexandreSantos The range is *not* important - it was chosen as a reasonable compromise in terms of memory usage. The ideal scenario would be to cache all integers, but you would impose quite serious heap size requirements if you did that. So you need to set a limit somewhere... It could have been different, it may be different in some JDK implementations and you can define it differently if you wish. – assylias May 05 '14 at 19:16
  • IMO it is good to have a cache for a certain number of `Integer`s in order to avoid creation of new instance of those immutable objects. On the other hand, if you want/need more `Integer`s to be cached, you could write your own cache or, even better, leverage this to the JVM and use a configuration for it. – Luiggi Mendoza May 05 '14 at 19:17
  • The same range -128 to 127 was chosen for Byte, Short, Character, Integer and Long. It appears they used the range of Byte by default to keep it simple. – Peter Lawrey May 06 '14 at 02:09

2 Answers2

0

To fit in one byte. From -256 to 255 is 512 numbers, which needs 9 bits. -128 to 127, the range of a signed byte, takes 8 bits, the capacity of one byte.

Ben N
  • 2,883
  • 4
  • 26
  • 49
0

Maybe they use a 1Byte int to store and index the cache, and a signed 1 Byte int is from -128 to 127. -256 to 255 can handled at least by a 2 Byte int and that is mybe too much and therefore to slow.

Biber
  • 709
  • 6
  • 19