Ramblings from a Bihari!

Just another WordPress.com weblog

interesting fact about identityHashCode() method in java.lang.System Class

The following four lines of code is provides such outputs which confused me about the identityHashCode() method of System class. System.identityHashCode() method is supposed to give the default hashcode value irrespective of whether you have overridden hascode in your class. And as we know that default implementation maps the internal memory address to an integer value.

1  String s = new String(new char[]{‘j’, ‘a’,’v’,’a’});
2  String s1 = new String(new char[]{‘a’, ‘b’,’c’,’d’});

3  System.out.println(System.identityHashCode(s));
4  System.out.println(System.identityHashCode(s1));

When I created a String instance by executing line 1 it would have got some memory location allocated to it. Lets say that is “x”. Then I created another instance s1 with passing some other different array to the String constructor. So s1 would have also got some memory location  allocated for it. Lets say that is “y”.

Now when I print the identity hash code by executing the line number 3 and 4 every time I run the program it gives me the same two integer values. And the order of values depends on the execution of line number 3 and 4 but not on 1 and 2 where actual allocation of memory happened. Thats strange for me 😦

Advertisements

July 31, 2008 Posted by | techie stuff | 8 Comments

Interesting inconsistency with java String pool

I was just trying out the intern() method of java.lang.String class and found an interesting issue.

The intern() method is supposed to put the string literal in the intern pool and give you back a handle to that.

Let me explain the scenario with two programs:-

public static void main(String[] args) {

char[] c = new char[]{‘a’,’b’,’c’};
String s = new String(c).intern();
System.out.println(System.identityHashCode(s));
s = null;
for (int i = 0; i < 20; i++) {
System.gc();
}
String s1 = new String(c).intern();
System.out.println(System.identityHashCode(s1));

}

What are the two values this program is supposed to print ?? I think since the intern is an WeakHashMap so after the gc call it should print two different values of identityHashCode.  Yes till now we are correct theortically and practically both.  But  if you replace the character array with any of

1. new char[]{‘a’,’b’,’c’};

2. new char[]{‘a’,’b’};

3. new char[]{‘a’};

The program will print both the hashcode values as same. Thats strange and very inconsistent. As per my understanding  the value of elements in the array should not be responsible for the behavior of intern() or any other java method.

July 31, 2008 Posted by | techie stuff | 1 Comment