I have to create a table with two type BitSet dimensions (9x9). I fulfills this table with bit values 1 to 9. I wish to withdraw a value of a particular case (exemple 5), but .set method (int, boolean) modifies all the boxes in my chart.
how to do ??
//create
private BitSet[][] solveur = new BitSet[9][9];
//init
BitSet BitInitialisation = new BitSet();
BitInitialisation.set(1, 10);
for (int ligne = 0; ligne < 9; ligne++) {
for (int colonne = 0; colonne < 9; colonne++) {
solveur[ligne][colonne] = BitInitialisation;
}
}
//read + method call
for (int ligne = 0; ligne < 9; ligne++) {
for (int colonne = 0; colonne < 9; colonne++) {
AjusterLigne(ligne ,5);
}
}
//method "AjusterLigne"
private void AjusterLigne(int ligne, int valeur) {
for (int colonne = 0; colonne < GrilleSudoku.MAX; colonne++){
solveur[ligne][colonne].set(valeur, false);
}
}
result: empty table...
You've created a 9x9 array of BitSet
references, but set every element value to the same reference - there's only a single BitSet
object involved. This is just a more complex version of this:
StringBuilder builder = new StringBuilder();
StringBuilder[] array = { builder, builder };
array[0].append("foo");
System.out.println(array[1]); // Prints foo
If you really want 81 independent BitSet
objects, you need to create 81 different BitSet
objects:
for (int ligne = 0; ligne < 9; ligne++) {
for (int colonne = 0; colonne < 9; colonne++) {
BitSet bitSet = new BitSet();
bitSet.set(1, 10);
solveur[ligne][colonne] = bitSet;
}
}
It's very important to understand why this is the case - it's basically a matter of understanding the difference between references and objects in Java, and it's worth spending some time making sure you're clear about it... it affects everything you do in Java, pretty much.
See more on this question at Stackoverflow