少言多的代碼,這裏的實驗,在我看來,回答了這個問題:
import java.util.BitSet;
public class BitSetExperiment {
public static void main(String[] args) {
BitSet bs0=new BitSet();
BitSet bs1;
System.out.println("created:\tLength,Size bs0: "+bs0.length()+" , "+bs0.size());
bs0.set(15);
System.out.println("set(15):\tLength,Size bs0: "+bs0.length()+" , "+bs0.size());
bs0.set(63);
System.out.println("set(63):\tLength,Size bs0: "+bs0.length()+" , "+bs0.size());
bs0.set(86);
System.out.println("set(86):\tLength,Size bs0: "+bs0.length()+" , "+bs0.size());
bs0.clear(86);
System.out.println("clear(86):\tLength,Size bs0: "+bs0.length()+" , "+bs0.size());
bs0.clear(63);
System.out.println("clear(63):\tLength,Size bs0: "+bs0.length()+" , "+bs0.size());
System.out.println("Cloning to bs1...\n");
bs1=(BitSet)bs0.clone();
System.out.println("Length,Size bs0: "+bs0.length()+" , "+bs0.size());
System.out.println("Length,Size bs1: "+bs1.length()+" , "+bs1.size());
}
}
輸出:
created: Length,Size bs0: 0 , 64
set(15): Length,Size bs0: 16 , 64
set(63): Length,Size bs0: 64 , 64
set(86): Length,Size bs0: 87 , 128
clear(86): Length,Size bs0: 64 , 128
clear(63): Length,Size bs0: 16 , 128
Cloning to bs1...
Length,Size bs0: 16 , 64
Length,Size bs1: 16 , 64
望着輸出,我發現了兩件事情:
- 當您清除更重要的位時,BitSet不會縮小其大小,但可能是使用其他機制來完成更多sophi作爲蜘蛛@Boris在他的評論中提出的建議。
- 在克隆位集合,原以及在可能的最小分配被表示(以64個比特爲因子)
如果'BitSet'修整它的大小時,在邊界處翻轉一個位的克隆,你會有退化的表現。如果'BitSet'自動調整大小,它可能會根據[最佳實踐](https://ece.uwaterloo.ca/~dwharder/aads/Algorithms/Array_resizing/)發生 - 這有點複雜比你的測試建議。 –
完全同意,很可能Java實際上修整了bitset,但在清除空間後卻不正確。我會在答案中提出這種可能性 – onlycparra