[英]How to create SortedSet (e.g. TreeSet) for elements of type BitSet
I have a number (power(2,k))
of BitSet objects and I want to store them in a SortedSet
. 我有一个数字(power(2,k))
的BitSet对象,我想将它们存储在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
但是,我收到此错误: 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
? 或者有没有其他方法来对BitSet
类型的这些元素进行排序?
There are two ways to use a TreeSet
. 有两种方法可以使用TreeSet
。
Comparable
它包含实现Comparable
对象 Comparator
object that compares the elements of your TreeSet
. 有一个自定义Comparator
对象,用于比较TreeSet
的元素。 Since you want to have your TreeSet
contain BitSet
s, and BitSet
does not implement Comparable
, you need to give your TreeSet
a custom Comparator
. 由于您希望TreeSet
包含BitSet
,并且BitSet
不实现Comparable
,因此您需要为TreeSet
提供自定义Comparator
。 How you implement that Comparator
is up to you. 你如何实现Comparator
取决于你。
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;
}
}
}
I would convert them to BigIntegers (O(N)) and use a TreeSet. 我会将它们转换为BigIntegers(O(N))并使用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. 我还会考虑使用PriorityQueue而不是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. 我不确定为什么要将BitSet放在treeSet中,而解决方法是创建一个实现Comparable接口的包装类 。
Public class CustomComparableBitSet implements Comparable{
private BitSet bs;
public int compareTo(T o){
//your comparison logic goes here.
}
}
then in the client code, add instance of CustomComparableBitSet into treeset . 然后在客户端代码中,将CustomComparableBitSet的实例添加到treeset中 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.