Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

java - How to make HashMap work properly with custom key type?

I think my question is quite simple, however I couldn't find the solution so I decided to ask here. What i need is to make a HashMap with a custom Key type like this:

HashMap<Pair<Integer, Integer>, StrategyPoint> myMap = new HashMap<Pair<Integer, Integer>, StrategyPoint> ();

However I am missing something here, because the HashMap stops working properly. First the Key becomes not unique and a different instances of Pair with same values can be found in the keySet. Also the contains key function does not work the way I suppose it to :).

I clearly miss something and more likely I should somehow define a way to compare my instances from my Pair class. However I tried implementing Comparable with compareTo in my Pair class and it still don't work. Any suggestions?

My original code is kinda messy and unfriendly to read, so I made an example just to illustrate my problem here.

Here is the code:

HashMap<Pair<Integer, Integer>, StrategyPoint> myMap = new HashMap<Pair<Integer, Integer>, StrategyPoint> ();
    Pair<Integer, Integer> myPair = new Pair<Integer, Integer>(2,2);
    StrategyPoint myPoint= new StrategyPoint(2, 2, 5, 5, false);
    myMap.put(myPair, myPoint);


    Pair<Integer, Integer> searcher = new Pair<Integer, Integer> (0,0);
    searcher.setFirst(2);
    searcher.setSecond(2);
    System.out.println(myMap.containsKey(searcher));
    System.out.println(myMap.containsKey(myPair));

The result from execution is:

false

true

I have debug it and the searcher instance is being populated properly, however it seems the HashMap refuse to find it in its keySet.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You must implement properly equals and hashCode on the Pair class.

The HashMap uses these methods to differentiate and hash the key class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...