top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Can we use any class as Map key in Java if yes how, if no then why not?

+1 vote
982 views
Can we use any class as Map key in Java if yes how, if no then why not?
posted Mar 14, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

Yes we can use any class as a map key in java,suppose we have a class name named MyMap so here is some description of MaMap class
See this example:

 //MyKey name argument passed is used for equals() and hashCode()
    MyKey key = new MyKey('Shivam Pandey'); //assume hashCode=1234
    myHashMap.put(key, 'Value');

    // Below code will change the key hashCode() and equals()
    // but it's location is not changed.
    key.setName('ShashiKant'); //assume new hashCode=7890

    //below will return null, because HashMap will try to look for key
    //in the same index as it was stored but since key is mutated, 
    //there will be no match and it will return null.
    myHashMap.get(new MyKey('Shivam Pandey'));

credits: https://www.javacodegeeks.com/2013/02/40-java-collections-interview-questions-and-answers.html#map-key

answer Mar 21, 2016 by Shivam Kumar Pandey
0 votes

Yes, we can use any class as a key in the map as long as the class implements equals and hashcode methods ..

answer Mar 22, 2016 by anonymous
...