collections - What causes the ClassCastException: java.util.TreeSet cannot be cast to java.lang.Comparable? -


so i'm trying move strings of length collection of strings (could either set or list) treemap , setting set of characters in each string key string line map.put(keyringer(word), word); throws java.lang.classcastexception: java.util.treeset cannot cast java.lang.comparable

map<set<character>, string> map = new treemap<set<character>, string>(); (string words : words)    {   if (word.length() == length)  {     map.put(keyringer(word), word);   } } 

this keyring method in case you're curious.

private set<character> keyringer(string current)  {    set<character> keyring = new treeset<character>();   (int = 0; < current.length(); i++)   {     char key = current.charat(i);      keyring.add(key);   }   return keyring; } 

so question can avoid this? i've read need comparator or implement comparable don't know how that, , think there might simpler solution (although perhaps not efficient).

you'll notice javadoc of treemap states

the map sorted according natural ordering of keys, or comparator provided @ map creation time, depending on constructor used.

so if don't provide comparator, use natural ordering. natural ordering? javadoc of comparable interface states

this interface imposes total ordering on objects of each class implements it. this ordering referred class's natural ordering, , class's compareto method referred natural comparison method.

so key element in treemap must implement comparable. trying use treeset instances keys in treemap. treeset not implement comparable.

you classcastexception when treemap tries cast key comparable reference in order use compareto method.

to correct issue, should create treemap providing own custom comparator comparing set<character> instances.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -