Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a char array as Hashtable key

Tags:

java

hashtable

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
like image 626
Ravi Joshi Avatar asked Aug 21 '26 13:08

Ravi Joshi


1 Answers

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.

like image 155
Louis Wasserman Avatar answered Aug 23 '26 04:08

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!