0

I have a Pair class and -

Map<Pair<String, String>, String> map = new HashMap<Pair<String, String>, String>();
map.put(new Pair("name1", "address1"), "Young");
map.put(new Pair("name2", "address2"), "Old");
.
.
. and so on.

Now I have a requirement where I have to treat two pairs as equal where

pair1 = new Pair("name1", "address1");
pair2 = new Pair("address1", "name1");

Note that pair2 in not as a key in the map but pair1 is. So that when I do

map.get(pair1);
map.get(pair2);

gives me same result as "Young";

What additional things should I do to achieve it?

Nihal Sharma
  • 2,065
  • 7
  • 34
  • 55

2 Answers2

2

You will have to override equals() and hashcode() in the Pair class. Also refer these https://stackoverflow.com/a/2265637/869488

https://stackoverflow.com/a/27609/869488 (check the 'Also remember' heading of these answer)

Community
  • 1
  • 1
rajesh
  • 3,081
  • 4
  • 28
  • 52
1

Override hashCode() and equals() method in Pair class so that,

pair1 = new Pair("name1", "address1");
pair2 = new Pair("address1", "name1");

will be in same hash bucket in a hashmap. When you do correctly override the hashCode() method to ensure that equal objects get equal hash codes, the hashmap is able to find the two equal objects and place them in the same hash bucket.

Abimaran Kugathasan
  • 26,826
  • 11
  • 67
  • 101