Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Map<K,V> : Why get(object) not get(K)? [duplicate]

Tags:

java

generics

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)?

like image 567
Marty Pitt Avatar asked Jul 16 '10 12:07

Marty Pitt


People also ask

Why duplicate keys are not allowed in HashMap?

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.

Does Map allow duplicates in Java?

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.

How do I store duplicates in maps?

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.


1 Answers

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?

like image 92
tonio Avatar answered Oct 07 '22 19:10

tonio