I think my question is quite simple, however I could not find a solution, so I decided to ask here. I need 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 donβt see something here because the HashMap stops working properly. First, the key becomes unique, and in the key set you can find different instances of the pair with the same values. Also, the key-key function does not work the way I assume it is :). I explicitly missed something, and most likely I need to somehow figure out how to compare my instances with my Pair class. However, I tried to implement Comparable with compareTo in the Pair class and still does not work. Any suggestions?
My source code is a bit dirty and unfriendly to read, so I made an example 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));
Execution Result:
falsely
True
I am debugging it and the crawler instance is populating properly, however it seems that the HashMap refuses to find it in its KeySet.
Thanks for helping the guys!