5

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

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.