Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Composite key in hashmaps

I would like to store a group of objects in a hashmap , where the key shall be a composite of two string values. is there a way to achieve this?

i can simply concatenate the two strings , but im sure there is a better way to do this.

like image 749
user1203861 Avatar asked Jul 28 '12 11:07

user1203861


People also ask

Can we pass object as key in HashMap?

Answer to your question is yes, objects of custom classes can be used as a key in a HashMap.

Why key in HashMap is immutable?

Immutabiility is required, in order to prevent changes on fields used to calculate hashCode() because if key object return different hashCode during insertion and retrieval than it won't be possible to get object from HashMap.

How do you make an employee object a key in HashMap?

If you want to make a mutable object as a key in the hashmap, then you have to make sure that the state change for the key object does not change the hashcode of the object. This can be done by overriding the hashCode() method. But, you must make sure you are honoring the contract with equals() also.

What happens if we put a key object in a HashMap which exists?

What happens if we put a key object in a HashMap which exists? Explanation: HashMap always contains unique keys. If same key is inserted again, the new object replaces the previous object.


2 Answers

You could have a custom object containing the two strings:

class StringKey {     private String str1;     private String str2; } 

Problem is, you need to determine the equality test and the hash code for two such objects.

Equality could be the match on both strings and the hashcode could be the hashcode of the concatenated members (this is debatable):

class StringKey {     private String str1;     private String str2;      @Override     public boolean equals(Object obj) {         if(obj != null && obj instanceof StringKey) {             StringKey s = (StringKey)obj;             return str1.equals(s.str1) && str2.equals(s.str2);         }         return false;     }      @Override     public int hashCode() {         return (str1 + str2).hashCode();     } } 
like image 97
Tudor Avatar answered Sep 17 '22 14:09

Tudor


You don't need to reinvent the wheel. Simply use the Guava's HashBasedTable<R,C,V> implementation of Table<R,C,V> interface, for your need. Here is an example

Table<String, String, Integer> table = HashBasedTable.create();  table.put("key-1", "lock-1", 50); table.put("lock-1", "key-1", 100);  System.out.println(table.get("key-1", "lock-1")); //prints 50 System.out.println(table.get("lock-1", "key-1")); //prints 100  table.put("key-1", "lock-1", 150); //replaces 50 with 150 

Happy coding!

like image 29
TMtech Avatar answered Sep 20 '22 14:09

TMtech