I have a number (power(2,k))
of BitSet objects and I want to store them in a SortedSet
. I use the code:
Set <BitSet> S= new TreeSet<>();
However, I am getting this error: java.lang.ClassCastException: java.util.BitSet cannot be cast to java.lang.Comparable
How do I implement comparable interface? Or is there any other way to sort these elements of type BitSet
?
I would convert them to BigIntegers (O(N)) and use a TreeSet. Otherwise you will have to write yourself a Comparator, which in the nature of things will run excruciatingly slowly, as you can see from other answers. I would also consider using PriorityQueue instead of a Set.
I'm not sure why you want to put BitSet in a treeSet, while a workaround is to create a wrapper class which implements Comparable interface.
then in the client code, add instance of CustomComparableBitSet into treeset.
There are two ways to use a
TreeSet
.Comparable
Comparator
object that compares the elements of yourTreeSet
.Since you want to have your
TreeSet
containBitSet
s, andBitSet
does not implementComparable
, you need to give yourTreeSet
a customComparator
. How you implement thatComparator
is up to you.The Comparator may look something like this