In TreeMap
the Comparator
is to compare the key rather than the value. The first get
and put
succeeded because the map is empty, and don't need to invoke your comparator. But the second get
requires the comparator to compare the key with the existing key. Your input key is String
type while the comparator process it as Student
type. Then a ClassCastException
is thrown.
Declare your map as:
Map<String, Student> students = new TreeMap<String, Student>();
then it will work. Note that you don't need to provide a Comparetor
for String
key type because String
is already Comparable
.