如何为BitSet类型的元素创建SortedSet(例如TreeSet) [英] How to create SortedSet (e.g. TreeSet) for elements of type BitSet

查看:80
本文介绍了如何为BitSet类型的元素创建SortedSet(例如TreeSet)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多(power(2,k))的BitSet对象,我想将它们存储在 SortedSet 。我使用代码:

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<>();

但是,我收到此错误: java.lang.ClassCastException:java .util.BitSet无法转换为java.lang.Comparable

However, I am getting this error: java.lang.ClassCastException: java.util.BitSet cannot be cast to java.lang.Comparable

如何实现可比较的接口?还是有其他方法可以对这些类型为 BitSet 的元素进行排序?

How do I implement comparable interface? Or is there any other way to sort these elements of type BitSet?

推荐答案

有两种方法可以使用 TreeSet


  1. 包含对象实现 Comparable

  2. 具有自定义 Comparator 对象的对象,该对象用于比较您的 TreeSet

  1. Have it contain objects that implement Comparable
  2. Have a custom Comparator object that compares the elements of your TreeSet.

因为您想拥有 TreeSet 包含 BitSet s,而 BitSet 不实现可比的,您需要给 TreeSet 一个自定义的比较器。如何实现比较器由您决定。

Since you want to have your TreeSet contain BitSets, and BitSet does not implement Comparable, you need to give your TreeSet a custom Comparator. How you implement that Comparator is up to you.

SortedSet<BitSet> s = new TreeSet<BitSet>(new CustomBitSetComparator());
s.add(bitSet1);
s.add(bitSet2);
//etc ...

比较器可能看起来像这样

The Comparator may look something like this

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;
         }
    }
}

这篇关于如何为BitSet类型的元素创建SortedSet(例如TreeSet)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆