Ahmad Fahmy
Ahmad Fahmy

Reputation: 327

Why does my original array gets changed when i only change copied array?

here i want to make duplicate array "arr" for my tile array and make some changes to it, the problem is when i make the changes (in method neighbors) it applies to the original array "tiles" too

public class Board {
    private final int [][] tiles;
    // construct a board from an n-by-n array of blocks
    // (where blocks[i][j] = block in row i, column j)
    public Board(int[][] blocks) {
        tiles = blocks;
    }// all neighboring boards
    public Iterable<Board> neighbors() {
        Queue<Board> q = new LinkedList<>();
        int [][] arr = tiles;
        // do stuff
        if (y+1 < n) {
            int t = arr[x][y];
            arr[x][y] = arr[x][y+1];
            arr[x][y+1] = t;
            Board br = new Board(arr);
            if(!this.equals(br)) {
                q.add(new Board(arr));
            }
        }
        return q;
    } 
}

thanks for your time

Upvotes: 0

Views: 134

Answers (3)

David Conrad
David Conrad

Reputation: 16359

You haven't copied the array, you've only copied a reference to the array. Both variables are referring to the same array. See this question to make a deep copy of the array: How do I do a deep copy of a 2D array in Java?

Upvotes: 0

Ollie in PGH
Ollie in PGH

Reputation: 2629

Arrays are objects in Java. Oracle doc

And objects are not duplicated in that manner. Your variables "tiles" and "arr" are just pointing at the same array now, you haven't copied it.

To copy an array try System.arraycopy:

System.arraycopy( tiles, 0, arr, 0, tiles.length );

See more about System copy here: https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy(java.lang.Object,%20int,%20java.lang.Object,%20int,%20int)

Upvotes: 1

csirmazbendeguz
csirmazbendeguz

Reputation: 620

In Java arrays are objects. You can use the clone() method to copy your array. It will perform a shallow copy - it will work fine with your int array.

int [][] arr = new int[tiles.length][];
for(int i = 0; i < tiles.length; i++)
    arr[i] = tiles[i].clone();
  1. copy a 2d array in java

Upvotes: 1

Related Questions