Can we use any class Map key
Answer: Yes we can use class as key of HashMap. HashMap store data based on hashing algorithm so before using class as key below point should be consider:
- Class should be immutable and if don’t keep it then hash code value can be change and when you try to pull value from hash map then possibility is you won’t get same value which you will see in below java class example
- Class must override hashcode() and equals() method
Please java class example below:
package com.javahonk.classaskey; import java.util.HashMap; import java.util.Map; public class ClassAsKey { public static void main(String[] args) { Map<Person, String> map = new HashMap<Person, String>(); Person person = new Person(); //Print hash code of person class System.out.println("Hash code: "+person.hashCode()); map.put(person, "Java Honk"); //Print hash code of person class again System.out.println("Hash code: "+person.hashCode()); //This will return same value System.out.println("Value: "+map.get(person)+"\n"); //Now check mutability, Because person class is //mutable let's change person name person.setName("Java Honk"); //Print hash code of person class again System.out.println("Hash code: "+person.hashCode()); //It will return you null because hash code has //been changed System.out.println("Value: "+map.get(person)); } } class Person{ private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
Output: