Pedro Barros
Pedro Barros

Reputation: 183

Duplicating Objects/Arrays in Java

I have an object with an array as parameter and I'm trying to copy that object in a way I can modify one without modifying the other. Here's my class:

public class Matrix {
 int rows[];

 Matrix() {
    rows = new int[9];
 }

 int[] getRows() {
    return rows;
 }

 void setRow(int x, int y) {
    rows[x] = y;
 }

 int getRow(int x) {
    return rows[x];
 }
}

I want to do something like:

(Consider Object Matriz x is all filled with values)
Matrix k = new Matrix();
k = x;
(Now I want to modify a specific column without of k without modifying a column of x)
k.setRow(3, 3);

But what happens is I get both arrays as same because of the reference when I do k = x;

How can I avoid this and duplicate them instead of creating references? I would like to avoid copying cell by cell to avoid an increase of the run time. (One solution is creating a primitive class Matriz with a sub-class Cell with int values, but besides that?)

Thanks

Upvotes: 2

Views: 59

Answers (3)

NiziL
NiziL

Reputation: 5140

You have to create a new Matrix. As rows is an array of integer, you can simply use Arrays.copyOf(rows, rows.length) to copy it.

There are two common ways:

1/ Create a constructor which take a Matrix as input:

public Matrix(Matrix matrix){
  this.rows = Arrays.copyOf(matrix.rows, matrix.rows.length);
}

then Matrix k = new Matrix(x);

2/ implements Cloneable:

@Override
public Matrix clone() {
  Matrix m = new Matrix();
  m.rows = Arrays.copyOf(this.rows, this.rows.length);
  return m;
}

then Matrix k = x.clone();

Of course, you can also mix these two approaches :)

Upvotes: 1

Eran
Eran

Reputation: 393771

First of all, you call your class Matrix, but it's not a matrix. It only has one dimension, so Vector would be more accurate.

In order to duplicate your instance, you can use a copy constructor.

Matrix(Matrix other) {
    rows = Arrays.copyOf(other.rows, other.rows.length);
}

You create a copy of x by :

Matrix k = new Matrix(x);

Upvotes: 2

Bene
Bene

Reputation: 734

You could make a second constructer that takes another Matrix as parameter and copys it.

public Matrix(Matrix matrix) {
   int[] matrixRows = m.getRows();

   this.rows = new int[matrixRows.length];
   for(int i = 0; i < matrixRows.length; i++) {
       this.rows[i] = matrixRows[i];
   }
}

Upvotes: 1

Related Questions