0

I came across a very weird behavior which later found to be a part of java specs. Let me put the relevant code from the said posting

 Integer a = 1000, b = 1000;
        System.out.println(a == b); //Prints false 

        Integer c = 100, d = 100;
        System.out.println(c == d); //Prints true

This quite similar to the String literal pool but with an exception that there is a limit to it. Let me quote again from Jon Skeet's reply to earlier mentioned post.

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Now my questions is, since we do not have a limit to the String Literal Pool, why not the same for other types ? What were the design/performance considerations for not having this? Is there any way its configurable?

Community
  • 1
  • 1
Santosh
  • 17,667
  • 4
  • 54
  • 79
  • Yes, its been there since Java 5.0 (2004) I've written more than enough on the subject. ;) – Peter Lawrey Dec 29 '11 at 13:39
  • You could have some sort of "literal pool" for the wrapped types, although the literals are actually primitives. But why bother? The interesting cases are for variable variables. And having `==` work differently when people are trying to test stuff out with constant values probably isn't going to be helfull. – Tom Hawtin - tackline Dec 29 '11 at 13:49

2 Answers2

0

since we do not have a limit to the String Literal Pool, why not the same for other types ?

Because the number of String literals in a set of Java classes is bounded, and probably rather low. On the contrary, the number of dynamically boxed Integer instances is not bounded (well, there are 2^32 possible values). Caching them all would consume gigabytes of memory, and would be counter-productive.

And I'm not even talking about all the other types: char, short, long, etc.

This simple program would lead to an OutOfMemoryError:

for (int i = 0; i < Integer.MAX_VALUE; i++) {
    Integer.valueOf(i);
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

Statistically speaking, low numbers appear much more often than large ones. Positive numbers appear more often than negative ones (all the 0 to n loops). 128 is a bit low for me, but 1024 would cover 99.9% of my numbers. I work in database backed enterprise systems in I never fetch more than 1024 lines from database. So none of my lists exceed that size and loops over them are the majority of numbers used (if I use numbers at all). Long IDs I represent with BigDecimal or BigInteger anyway, and only other long numbers I used is UNIDs for searializable interface which is final and long.

I reckon it isn't worth it for most developers to cache large Integer objects. Besides, you should use equals metod not ==. I never use == unless I'm dealing with primitives.

RokL
  • 2,663
  • 3
  • 22
  • 26