Although String implements CharSequence, Java does not allow this. What is the reason for this design decision?
Asked
Active
Viewed 2,235 times
5
-
2http://stackoverflow.com/questions/7098402/implementations-and-collections/7098461#7098461 – zw324 Aug 18 '11 at 18:20
-
possible duplicate of [Any simple way to explain why I cannot do List
animals = new ArrayList – Daniel Pryden Aug 18 '11 at 20:14()?](http://stackoverflow.com/questions/2346763/any-simple-way-to-explain-why-i-cannot-do-listanimal-animals-new-arraylistdo)
2 Answers
6
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.
3
It should be HashMap<? extends CharSequence, ? extends CharSequence>

Reverend Gonzo
- 39,701
- 6
- 59
- 77