Question

When I am in my class and ,I create a new instance of the class within that class,say instance i, and then I change that instance also within that class both of the instances are changed; where I only want instance i to be changed.

The class is called Square.

This effect is demonstrated in a test function of Square.

void testFunction() {
    Square tempSqr = new Square(x + 1, myTiles, blankIndex);
    this.toPrint();
    // tempSqr.toPrint();
    tempSqr.switchTile(1, 2);// switch is editing parent nodes
    // tempSqr.toPrint();
    this.toPrint();
}

This produces the output

1 2 3
4 5 6
7 8 0

----this is not part of the output but is here for formatting for stackoverflow

1 2 3
4 5 6
7 0 8

Notice after tempSqr.switchTile(); this.Square(); changes. This is not what I want, I want only tempSqr to change. By the way tempSqr is changing.

Here is switchTile():

public void switchTile(int myX, int myY) {
    Iterator<Tile> e = myTiles.iterator();
    int counter = 0;

    while (e.hasNext()) {
        Tile t = e.next();

        if (myX == t.getX() && myY == t.getY()) {
            Tile blank = myTiles.get(blankIndex);
            int tx = t.getX();
            int ty = t.getY();
            // /////
            int bx = blank.getX();
            int by = blank.getY();
            // /////////
            t.setX(bx);
            t.setY(by);
            blank.setX(tx);
            blank.setY(ty);
            // /////////////
            myTiles.set(counter, t);
            myTiles.set(blankIndex, blank);
        }
        counter++;
    }
}

The rest of the code is https://github.com/danielGood/AISearchDemo in case you're interested. Any help would be greatly appreciated, I have already spent a good deal of time on this error. Thank in advance.

Was it helpful?

Solution

Your problem lies with myTiles.

In the first line, you are creating a new Square, but passing in the same set of tiles. Thus, both squares have a reference to the same set of tiles.

You need to perform a deep copy on myTiles

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top