Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I set HashMap<CharSequence,CharSequence> to HashMap<String,String>

Tags:

java

generics

Although String implements CharSequence, Java does not allow this. What is the reason for this design decision?

like image 247
Brent Avatar asked Aug 18 '11 18:08

Brent


People also ask

Can the key in a HashMap be a String?

String is as a key of the HashMap When you create a HashMap object and try to store a key-value pair in it, while storing, a hash code of the given key is calculated and its value is placed at the position represented by the resultant hash code of the key.

Can we convert map to String in Java?

Use Object#toString() . String string = map. toString();

Can we convert map to String?

We can convert a map to a string in java using two array lists. In this, we first fill the map with the keys. Then, we will use keySet() method for returning the keys in the map, and values() method for returning the value present in the map to the ArrayList constructor parameter.

How do you add a value to a String object on a map?

The standard solution to add values to a map is using the put() method, which associates the specified value with the specified key in the map.


2 Answers

The decision to disallow that was made because it's not type-safe:

public class MyEvilCharSequence implements CharSequence
{
    // Code here
}

HashMap<CharSequence, CharSequence> map = new HashMap<String, String>();
map.put(new MyEvilCharSequence(), new MyEvilCharSequence()); 

And now I've tried to put a MyEvilCharSequence into a String map. Big problem, since MyEvilCharSequence is most definitely not a String.

However, if you say:

HashMap<? extends CharSequence, ? extends CharSequence> map = new HashMap<String, String>();

Then that works, because the compiler will prevent you from adding non-null items to the map. This line will produce a compile-time error:

// Won't compile with the "? extends" map.
map.put(new MyEvilCharSequence(), new MyEvilCharSequence());

See here for more details on generic wildcards.

like image 58
dlev Avatar answered Oct 23 '22 10:10

dlev


It should be HashMap<? extends CharSequence, ? extends CharSequence>

like image 39
Reverend Gonzo Avatar answered Oct 23 '22 11:10

Reverend Gonzo