Classes like Integer, String, Double etc implements Comparable interface. So if we are to use an object of a custom class as the key, ensure that it’ s class implements the Comparable interface.
public class MyCustomKey implements Comparable { private int value; public MyCustomKey(int value) { this.value = value; } public int compareTo (MyCustomKey key) { int comparison = 0; // Note: // Return -1 if this.value < key.value // Return 0 if this.value = key.value // Return 1 if this.value > key.value return (comparison); } }
A common mistake that everyone does is not to override the hashcode(). If we are failing to do so, map.get(new MyCustomKey(
public class MyCustomKey implements Comparable { private int value; public MyCustomKey(int value) {} public int compareTo (MyCustomKey key) {} public int hashCode() { // Note: // If two objects are equal then their corresponding hashCode () // should return the same value too. return (this.value * 199); } }
When you are using your custom object as a key to a HashMap, make sure you do the following
1) implement Comparable
2) override compareTo method, and give its implementation
3) override hashCode and equals method, and give their implementation.
4) Always, make your key object as immutable, so that it is not changed after you add it to a HashMap as key.
No comments:
Post a Comment