5

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

skaffman
  • 398,947
  • 96
  • 818
  • 769
Brent
  • 53
  • 3
  • 2
    http://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()?](http://stackoverflow.com/questions/2346763/any-simple-way-to-explain-why-i-cannot-do-listanimal-animals-new-arraylistdo) – Daniel Pryden Aug 18 '11 at 20:14

2 Answers2

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
dlev
  • 48,024
  • 5
  • 125
  • 132
3

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

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