I’m a Java noob with a bit of C++ experience and I’m trying to create a Set of Sets in Java along the following lines (similar to what one would do in C++):
Set< Set< String > > collection = new TreeSet< Set< String > >();
Set< String > entry = new TreeSet< String >();
collection.add( entry );
This builds fine, but then when the program is executed, a java.util.TreeSet cannot be cast to java.lang.Comparable exception is thrown.
Without reimplementing the wheel, how can one have a Set of Sets in Java?
Also, what is the deal with Java allowing broken code (e.g., the type mismatch) to compile?
Thanks in advance for any feedback.
In the contract of
TreeSet, the requirement is laid out that all entries have to beComparableor you have to provide aComparator. (This is also why you didn’t see a compile-time error: entries are only cast toComparablein the absence of an explicitComparator.)It’s got nothing to do with generics, it comes from the implementation of
TreeSetitself: as it’s a binary tree, it only makes sense if the entries can be ordered somehow.If you tell a bit more about your specific problem, we can probably help you find the exact data structure you need but in general, if you don’t care about the order of elements in a set, a
HashSetis used. And again, in general, aSetofSets is often a sign of sloppy design.