Although String implements CharSequence, Java does not allow this. What is the reason for this design decision?
String is as a key of the HashMap When you create a HashMap object and try to store a key-value pair in it, while storing, a hash code of the given key is calculated and its value is placed at the position represented by the resultant hash code of the key.
Use Object#toString() . String string = map. toString();
We can convert a map to a string in java using two array lists. In this, we first fill the map with the keys. Then, we will use keySet() method for returning the keys in the map, and values() method for returning the value present in the map to the ArrayList constructor parameter.
The standard solution to add values to a map is using the put() method, which associates the specified value with the specified key in the map.
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.
It should be HashMap<? extends CharSequence, ? extends CharSequence>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With