Possible Duplicate:
Java Generics: Why Does Map.get() Ignore Type?
Could someone please explain why with Map defines
V put(K key,V value);
V get(Object key);
Why is get
not defined as:
V get(K key)
Similarly, why are these methods typed to Object
, and not K
and V
respectively?
boolean containsKey(Object key); // Why not K?
boolean containsValue(Object value); // Why not V?
Is this a backwards compatibility thing (pre 1.5)?
Implementation: HashMap implements Map interface and HashSet implements Set interface. Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
Map does not supports duplicate keys. you can use collection as value against same key. Because if the map previously contained a mapping for the key, the old value is replaced by the specified value.
Let's see how to store our multiple values into an ArrayList, which retains duplicates: MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); map. put("key1", "value1"); map. put("key1", "value2"); map.
Good explanations can be found in the answers of
What are the reasons why Map.get(Object key) is not (fully) generic
and
Java Generics: Why Does Map.get() Ignore Type?
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