Aliasing in 2 Dimensional Arraylists
807589Nov 12 2008 — edited Nov 12 2008Hello Everyone,
I have got a question on 2D arraylists. When I copy an 2D arraylist and make changes to the copy, It also applies the changes to original copy. This is know as aliasing, if I am right. I need an original copy of the arraylist.
Any response would be appreciated. The following is my code that I implemented in netbeans IDE 6.1.
import java.util.ArrayList;
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
//import java.awt.RenderingHints.*;
class test {
public test() {
test2();
}
public static void main (String [] param) {
new test();
}
public void test2() {
int num=0;
ArrayList [][] array1 = new ArrayList [6][6];
for (int x = 0; x < array1.length; x++)
{
for (int y = 0; y < array1[x].length; y++)
{
array1[x][y] = new ArrayList();
}
}
/*The following for loop is fillling the arraylist*/
for (int i=0; i < array1.length; i++) {
for (int j=0; j<array1.length; j++) {
if (((num/2)*2)==num) {
// num = -1;
array1[i][j].add("s");
}
if (((num/2)*2)!=num) {
// num = +1;
array1[i][j].add("h");
}
num++;
}
num=num+1;
}//end ou
/*The following for loops just prints the 2d arraylist on to the board*/
int k=0, l=0;
System.out.println("----------------------\n");
for (k=0; k<array1.length; k++) {
for (l=0; l<array1.length; l++) {
System.out.print(array1[k][l]);
}
System.out.print("\n");
}
System.out.println("----------------------\n");
test1(array1); // passing
} // end methos test2
public void test1(ArrayList [][] arrayCopy) {
ArrayList [][] array2 = new ArrayList [6][6];
int m=0, n=0;
array2 = arrayCopy.clone();
System.out.print("\ntest" + arrayCopy[0][1]);
for (m=0; m<arrayCopy.length; m++) {
//array2[m] = arrayCopy[m];
for (n=0; n<arrayCopy.length; n++) {
//array2[m] = arrayCopy[m];
array2[m][n].addAll(arrayCopy[m][n]);
// array2[m][n].add(arrayCopy[m][n].get(0));
}
}
array2 [1] [1].add("w");
array2 [0] [0].add("q");
// this is where i make changes to the copy of arraylist and print the copy of array
System.out.println("changes made to the copy of array----------------------\n");
for (int k=0; k<array2.length; k++) {
for (int l=0; l<array2.length; l++) {
System.out.print(array2[k][l]);
}
System.out.print("\n");
}
System.out.println("----------------------\n");
// this is where i print the original array to see if changes has effected it.
System.out.println("this should be original array----------------------\n");
for (int k=0; k<arrayCopy.length; k++) {
for (int l=0; l<arrayCopy.length; l++) {
System.out.print(arrayCopy[k][l]);
}
System.out.print("\n");
}
System.out.println("----------------------\n");
} // end method test1
} // end class