简体   繁体   中英

Using a char array as Hashtable key

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

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM