Monday, June 9, 2014

java integer pool

Here in this post, I record a bug in my project(Java).
The problem is when compare two integers, it works well only when integer is of one-byte length.
This is caused by "Integer constant pool". To avoid extra memory cost, Java will return a already-created Integer object if it's between -128 and 127. This means:
Integer i = Integer(10); Integer j = Integer(10);
bool flag = (i==j); //return true; directly check the address
bool flagE = i.equals(j);//return true; directly check the values, what we expect here.
For the Object class, which is the root class of all classes in java, these two method (or operator) are the same. But for a certain derived class, it is not necessary depends on the logic.

So if the logic of your program is to check whether two integers are equally valued, then you need to use equals instead of == operator.

You may imply that java override the equals function for Integer class. this gives us another topic to discuss, that is, when you override equals function you need override hashCode(). One naturally raised question is "why always override hashcode() given equals() overrided". Here is a good article for this question:
http://www.xyzws.com/javafaq/why-always-override-hashcode-if-overriding-equals/20
To simplify it, you have to guarantee that:
if equals(Object o) gives true, hashCode() output same integer. This means you need to generate hash code from attributes which are used to decide whether two objects are equal (equals() function).

No comments:

Post a Comment