I am very confused.
This is my understanding of basic variable and assigning values:
int a = 9;
int b = a;
int a = 8;
System.out.println(b); // This will be 9
Now I am trying the same thing but instead of basic types I am using an ArrayList two dimensional structure, see the following code:
public final class Matrix {
private List<List<Double>> rawMatrix = new ArrayList<List<Double>>();
private List<List<Double>> matrix = new ArrayList<List<Double>>();
private void update(){
matrix = rawMatrix;
System.out.println("matrix: "+matrix.size()+", "+matrix.get(0).size());
System.out.println("matrix: "+rawMatrix.size()+", "+rawMatrix.get(0).size());
matrix.get(0).add(99.0);
System.out.println("matrix: "+matrix.size()+", "+matrix.get(0).size());
System.out.println("matrix: "+rawMatrix.size()+", "+rawMatrix.get(0).size());
}
}
The problem is this output:
matrix: 4, 3
matrix: 4, 3
matrix: 4, 4
matrix: 4, 4
Now for some reason, rawMatrix
has added an element the same as matrix
even though I have never added anything onto the rawMatrix
structure.
I assume this is some weird type of assigning variable by reference, I don't quite understand why this is the case and why it's the default in Java.
How do I overcome this? Do I have to use two for loops to make one of my matrix's equal the other, that seems very inefficient.