Proper use of hashtable with custom class

This piece of code generates unexpected output.

Hashtable<Pair, Integer> results = new Hashtable<Pair, Integer>();
results.put(new Pair(0, 1), 2);
System.out.println("[DBG] " + results.containsKey(new Pair(0, 1)));

Output signal [DBG] false. Why Hashtablecould not register this item? Does this have anything to do with the way I'm trying to pass a Pairhash table?

+3
source share
2 answers

You must redefine hashCode()and equals(..)your class Pairto indicate that the two objects with the same number are equal. (Better let your IDE generate these 2 methods for you.)

Hashtable hashCode() . Pair, Object , , , Hashtable ( )

, , HashMap Hashtable. .

+8

new Pair(0,1). , :

- hashCode Pair.

, :

Hashtable<Pair, Integer> results = new Hashtable<Pair, Integer>();
Pair key=new Pair(0, 1)
results.put(key, 2);
System.out.println("[DBG] " + results.containsKey(key));
+2

Source: https://habr.com/ru/post/1772398/


All Articles