I want to copy my elements from a List<Set<String>> into a SortedMap<Set<String>,Integer>,
but I always get:
java.lang.ClassCastException: java.util.HashSet cannot be cast to java.lang.Comparable. (or HashMap could be a TreeSet too, vice versa)
Some places I’ve been reading say it isn’t possible, but is this correct?
I can’t believe I can’t copy a original List or Set into a Map.
This is what I have tried:
List<Set<String> > tempnewOut= new ArrayList<>();
SortedMap<Set<String>,Integer> freqSetsWithCount= new TreeMap<>();
for (Set<String> set : tempnewOut)
{
freqSetsWithCount.put(set, 0);
}
The class that you use as a key in a
TreeMap(one of the implementations of interfaceSortedMap) must either implement interfaceComparable, or you must create theTreeMapby providing aComparatorto the constructor.You’re trying to use a
HashSet<String>for the keys.HashSetdoesn’t implementComparable, and you’re not supplying aComparator, so you get aClassCastException.One solution is to create the
TreeMapby passing it aComparatorto the constructor. You’ll have to implement thecomparemethod of theComparatorto specify how the sets should be sorted in the map.