Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
@juny: i don't think there's a concept of HashMap in C#. Dictionary is a close match in which if you try to add two entries with the same key, it throws an exception. you need to first check the dictionary using the ContainsKey() method
If you use the indexer and assignment operator instead of Add for a C# Dictionary, it will add if it's not there and replace if it is.
"What will happen if two different objects have same hashcode?”
call keys.equals() method to identify correct node in LinkedList and return associated value object for that key in Java HashMap
"Since hashcode is same, bucket location would be same and collision will occur in HashMap, Since HashMap use LinkedList to store object, this entry (object of Map.Entry comprise key and value ) will be stored in LinkedList.
If two different objects have the same hashCode, what happens depends on the output of equals. If key2.equals(key1), then (key1, val1) is replaced with (key2, val2), else a new entry (key2, val2) is added to the same bucket of the hash map.
Please note that hashCode determines which bucket the key-val pair goes to while equals determines whether the object exists on not.
A more interesting question would be "What happens if two objects that are équal' returns different hash codes". In that case, they would hash to different buckets and hence will result in duplicate entries.
1. If the key is a duplicate, then the value is overwritten. Here is code to demonstrate that:
import java.util.Map;
import java.util.HashMap;
public class DuplicateEntriesAreNotAllowed {
public static void main(String[] args) {
Map<Integer,String> map = new HashMap();
map.put(1, "a");
map.put(1, "b");
System.out.println(map.entrySet());
}
}
2. If 2 objects have the same hashCode and they are not equal, then that key value pair will be put in the hash table.
If the key's match then the value is overwritten. In this case you have Integers as keys and since the key's match, during the second put() operation, "tom" would overwrite the previous value (which incidentally was tom) for key = 1
- Anonymous December 27, 2012