[英]BitSet is not working for Integer.MAX_VALUE and Integer.MIN_VALUE
I tried to use BitSet(java) to find the common numbers in two arrays. 我试图使用BitSet(java)在两个数组中查找公用数字。 (It seems works very well on finding repeating chars), however, when I tried the corner case such as Integer.MAX_VALUE (it cannot show up in the res) and Integer.MIN_VALUE( it shows IndexOutOfBoundsException("bitIndex < 0: " + bitIndex)) I thought the BitSet size is auto expandable.
(在查找重复的字符时看起来效果很好),但是,当我尝试使用Integer.MAX_VALUE(无法在res中显示)和Integer.MIN_VALUE(它显示IndexOutOfBoundsException(“ bitIndex <0:” + bitIndex))我认为BitSet的大小可以自动扩展。 Anyone can figure it out?
任何人都可以弄清楚吗? Thanks.
谢谢。 BitSet is so handy.
BitSet非常方便。 :)
:)
public static List<Integer> common(List<Integer> A, List<Integer> B) {
List<Integer> res = new ArrayList<Integer>();
BitSet bitSetA = new BitSet();
BitSet bitSetB = new BitSet();
for (Integer x : A) {
bitSetA.set(x);
}
for (Integer x : B) {
bitSetB.set(x);
}
bitSetA.and(bitSetB);
for (int i = 0; i < bitSetA.size(); i++) {
if (bitSetA.get(i)) {
res.add(i);
}
}
return res;
}
public static void main(String[] args) {
List<Integer> A = new ArrayList<Integer>();
A.add(1);A.add(2);A.add(Integer.MIN_VALUE);
List<Integer> B = new ArrayList<Integer>();
B.add(Integer.MIN_VALUE);B.add(4);B.add(4);
List<Integer> res = new ArrayList<Integer>();
res = common(A,B);
System.out.println(res);
}
} }
BitSet
indexes must not be negative; BitSet
索引不得为负。 see the third sentence of the javadoc . 参见javadoc的第三句。
Integer.MIN_VALUE
is negative and thus is not a valid index. Integer.MIN_VALUE
为负,因此不是有效的索引。
Integer.MAX_VALUE
works for me, as long as: 只要满足以下条件,即可使用
Integer.MAX_VALUE
:
there is sufficient heap space available, which is not the case by default in a 32-bit JVM, at least not the Oracle 32-bit JVMs I have conveniently to hand. 有足够的可用堆空间,默认情况下,在32位JVM中不是这样,至少我方便使用的Oracle 32位JVM并非如此。 A little experiment finds
-Xmx
of about 400m per maximal BitSet
is enough. 一个小实验发现,每个最大
BitSet
大约400m的-Xmx
就足够了。 (I'd bet the actual usage is 256m, but -Xmx
is a crude tool that includes several heap spaces and some overhead.) (我敢打赌,实际使用量为256m,但
-Xmx
是粗略的工具,其中包含多个堆空间和一些开销。)
you don't use length()
or size()
(or toString()
) which malfunction at the maximal size. 您不要使用以最大大小发生故障的
length()
或size()
(或toString()
)。 If I loop naively (as your code does) up to Integer.MAX_VALUE
it works but takes about a minute; 如果我天真地循环(如您的代码那样)直到
Integer.MAX_VALUE
它就可以工作,但是大约需要一分钟; the nextSetBit
approach shown in the javadoc is hugely faster. javadoc中显示的
nextSetBit
方法要快得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.