简体   繁体   中英

How to handle BitSet type table with the BitSet methods?

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.

That's because Java uses object references.

solveur[ligne][colonne] = BitInitialisation;

Here you've assigned a reference to BitInitialisation in all 81 cells. Modification of any of these will modify the same object. I can propose two solutions:

  1. You can create new BitSet on every iteration of the inner loop. (That's covered by @JonSkeet answer.)
  2. You can call .clone() method on the BitSet object.

    solveur[ligne][colonne] = BitInitialisation.clone();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM