011101,001110,110110,001111,000001,000100
我正在尝试用有关 int 数组的信息填充 BitSet 数组
//ar is a SIZE*SIZE 1-D int array, SIZE is a constant
//decare BitSet array
BitSet bs[] = new BitSet[SIZE];
//initialize BitSet array
for (BitSet x:bs)
x = new BitSet();
//populate BitSet array
for (int i = 0 ; i < ar.length ; i++)
if (ar[i] > 0)
bs[(i/SIZE)].set(SIZE-(i%SIZE));
最后一行似乎是问题所在,但我看不出逻辑有什么问题。 有什么想法吗?
为了更清楚地说明这一点,如果我有一个像
0,3,4,5,0,1,0,0,1,2,7,0,2,3,0,3,2,0,0,0,2,1,5,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,我想得到一个可以表示为
你的问题是对增强的 for 循环的误解。基本上:
for (BitSet x:bs)
x = new BitSet();
只是一块合成糖。编译器将其扩展为以下内容:
for (int i = 0; i < bs.length; i++) {
BitSet x = bs[i];
x = new BitSet();
}
在这个扩展中,很明显,你只是将新的位集分配给x
并将其丢弃。您实际上根本没有修改数组。您需要按如下方式初始化数组:
for (int i = 0; i < bs.length; i++) {
bs[i] = new BitSet();
}
在java中,你的'foreach'结构是这样的:
for (BitSet x:bs)
x = new BitSet();
// is the same as:
for (int i = 0; i < bs.length; i++) {
BitSet x = bs[i];
x = new BitSet();
}
你的问题是你没有赋值回数组,并且没有办法用'foreach'结构来做到这一点。你必须使用普通的"for"循环:
for (int i = 0; i < bs.length; i++) {
bs[i] = new BitSet();
}
您正在将新创建的对象分配给临时变量x
尝试如下内容。
int i=0;
for (BitSet x:bs)
{
x = new BitSet();
bs[i++] = x; //This will initialize the array elements
}