Although String implements CharSequence, Java does not allow this. What is the reason for this design decision?
-
2stackoverflow.com/questions/7098402/…zw324– zw3242011-08-18 18:20:19 +00:00Commented Aug 18, 2011 at 18:20
-
possible duplicate of Any simple way to explain why I cannot do List<Animal> animals = new ArrayList<Dog>()?Daniel Pryden– Daniel Pryden2011-08-18 20:14:59 +00:00Commented Aug 18, 2011 at 20:14
Add a comment
|
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.