Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

I want to store the number (power(2,k)) of BitSet objects in a SortedSet. Below is the code I’ve for that:

Set <BitSet> S= new TreeSet<>();

But it gives me an error: java.lang.ClassCastException: java.util.BitSet cannot be cast to java.lang.Comparable

Can anyone tell me how I can implement a comparable interface to sort the elements of type BitSet?

1 Answer

0 votes
by (19.7k points)

TreeSet has BitSets but BitSet does not implement Comparable, so you have to give the TreeSet a custom Comparator. See the code below:

SortedSet<BitSet> s = new TreeSet<BitSet>(new CustomBitSetComparator());

s.add(bitSet1);

s.add(bitSet2);

//etc ...

Below is the code for the Comparator :

class CustomBitSetComparator implements Comparator<BitSet>{

    int compare(BitSet a, BitSet b) {

        if(a == b){

            return 0;

        } else if(a == null) {

            return -1;

        } else if(b == null) {

            return 1;

        } else if(a.equals(b)) {

            return 0;

        } else if(a.length() > b.length()) {

            return 1;

        } else if(b.lenght() > a.length()) {

            return -1;

        } else {

            for(int i = 0; i < a.length(); i++) {

               if(a.get(i) != b.get(i)) {

                   if(a.get(i)) {

                      return 1;

                   } else {

                      return -1;

                   }

                }

             }

             return 0;

         }

    }

}

Interested in Java? Check out this Java tutorial by Intellipaat.  

Browse Categories

...