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.
Answer to your question is yes, objects of custom classes can be used as a key in a HashMap.
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.
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? Explanation: HashMap always contains unique keys. If same key is inserted again, the new object replaces the previous object.
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(); } }
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With