InterviewSolution
| 1. |
How Can We Use Any Class As Map Key? |
|
Answer» If we can use any CLASS as MAP key, follow these POINTS: The class always follows the basic rule optimized with hashCode() and equals() for all instances. If class filed is not used in equals () method, you should not utilize in hashCode() method. When the class OVERRIDES equals () method, it always overrides hashCode() method. Example: Suppose I have a class MyFirstKey then I am USING a HashMap key. //MyFirstKey name argument passed is used for equals() and hashCode() MyFirstKey key = new MyFirstKey('Meraj Ansari'); //assume hashCode=1234 myHashMap.put(key, 'Value'); // Below code will change the key hashCode() and equals() // but its location is not changed. key.setName('Deepak Gupta'); //assume new hashCode=98390 myHashMap.get(new MyFirstKey('Meraj Ansari')); If we can use any class as Map key, follow these points: The class always follows the basic rule optimized with hashCode() and equals() for all instances. If class filed is not used in equals () method, you should not utilize in hashCode() method. When the class overrides equals () method, it always overrides hashCode() method. Example: Suppose I have a class MyFirstKey then I am using a HashMap key. //MyFirstKey name argument passed is used for equals() and hashCode() MyFirstKey key = new MyFirstKey('Meraj Ansari'); //assume hashCode=1234 myHashMap.put(key, 'Value'); // Below code will change the key hashCode() and equals() // but its location is not changed. key.setName('Deepak Gupta'); //assume new hashCode=98390 myHashMap.get(new MyFirstKey('Meraj Ansari')); |
|