I am using java.util.HashMap for association between a contact Name and a list of phone numbers associated with the contact so it is of type String, List<String>. However there can be more than one keys that can map to the the same bucket correct as in Say key1:<1234,5678> is stored in index 2 in the hash Map. I could have another key2 that can hash into the same index. So, will the key1:<1234,5678> be replaced by key2:<7890,1456> ???? Or will it be chained and both key1 and key2 will be stored in that index ?
EDIT:
I’m trying to understand this, the code below only returns New Mexico. Now in this case both they both get the same hashcode so this is a collision correct ? In that case shouldn’t both the values be chained ? So shouldn’t the storage look like say hashcode is 2 then at the index of 2 in the map (OR array) it should be 1-Mexico, 1-New mexico correct? So the values returned should be of Mexico and New mexico ? Why isn’t it getting chained here ?
public static void main(String[] args)
{
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1, "Mexico");
map.put(1, "New Mexico");
System.out.println(map.get(1));
}
I’m not totally sure I understand your question.
In a standard HashMap, if you put another value with the same key, it replaces the first one.
But you may use for example a MultiMap (from Apache commons) to store more than one value per key.
If your question is related to more than one key having the same index, this is handled by the implementation : the keys for are stored in linked lists (one for each bucket) and real comparisons (using
equals) are done on get and put operations so that no collision can happen as long asequalsreturns false.As with any collection related problem, the important thing to do if you intend to use your own class is to correctly implement the
equalsandhashcodemethods (read this).Regarding your question in edit :
This is a feature of HashMap that the first value with a given key is erased by the new one. So “Mexico” is removed from the HashMap when you add “New Mexico”.
If you want to have more than one value for a given key, use a MultiMap (or simply use a
HashMap<Integer, List<String>>but theputoperation is a little more tedious).