2

I am working with Hashtable in my java program. I just surprised by seeing the abnormal behavior of Hastable. Below is my code (This is not my final code, i simply created a new simple project with the code which is running abnormal)

    Hashtable<char[], char[]> h1 = new Hashtable<char[], char[]>();
    char[] key = Integer.toString(12).toCharArray();
    char[] val = Integer.toString(21).toCharArray();
    h1.put(key, val);
    System.out.println(h1.containsKey(Integer.toString(12).toCharArray()));// Should print true, since 12 is there in Hashtable
3

3 Answers 3

8

You can't use arrays like this as map keys, because arrays have the default, referential-equality-based Object implementations of equals and hashCode. Using String as the key instead would make your program work as desired.

Sign up to request clarification or add additional context in comments.

3 Comments

But I've used arrays of integers. I didn't face any problems.
@crucified You did, maybe you just didn't notice it.. But since the basic statement ("arrays have referential equality") is true for any array, that's just how it is.
@Voo is right. int[] a = {1}; int[] b = {1}; System.out.println(a == b) prints false.
4

Array equality is based on referential equality ("Are these two references to the same object?") not deep equality ("Are these two objects semantically identical?"). Look:

char[] one = Integer.toString(12).toCharArray();
char[] two = Integer.toString(12).toCharArray();
System.out.println(one == two); // false

http://ideone.com/YwEjV

2 Comments

They aren't referring to the same object. In my above code, i used Integer.toString(). But in my actual code, i am working with char[]. So what can be done now?
Use Strings, not char[]s, as map keys. Also, you probably should be using HashMap instead of the legacy Hashtable. ...Also it would improve the code clarity to write "12".toCharArray() or new char[]{'1', '2'} instead of Integer.toString(12).toCharArray().
2

if a and b are 2 arrays than a.equals(b) if a == b. So hashCode of a == hashCode of b if a == b. Since this is not the case here, it will not be found in the hashtable. Using arrays as hashtable keys is a bad idea. Also using any mutable object as a hashtable key is a bad idea.

2 Comments

Your logic is not completely sound, since (in practice) the .equals() and .hashCode() method implementations are independent.
Part of the contract of equals and hashCode is to be consistent between each other. I would assume that Java follows it's own contract.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.