Why can't I set the HashMap <CharSequence, CharSequence> to HashMap <String, String>
2 answers
The decision to ban was made because it is not 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 tried to put MyEvilCharSequence in a String map. A big problem, since MyEvilCharSequence definitely not a String .
However, if you say:
HashMap<? extends CharSequence, ? extends CharSequence> map = new HashMap<String, String>(); Then it works, because the compiler will stop you from adding non- null elements to the map. This line will result in a compile-time error:
// Won't compile with the "? extends" map. map.put(new MyEvilCharSequence(), new MyEvilCharSequence()); See here for general wildcards for more details .
+6