I am trying to create a copy to an Array List of Array Lists, but when doing so the addresses of all the individual elements are staying the same.
copySorted = new ArrayList<ArrayList<String>>(origSorted);
I would expect to generate a copy of origSorted without references to the original, but instead whenever I make a change to copySorted, it ends up happening to origSorted as well. I also tried the .clone() function with the same results.
CodePudding user response:
It's not the changes to copySorted
you're seeing, it's changes to the inner lists which are shared between the outer lists. If you want them to be completely distinct, you'll need to copy each one individually:
copySorted = new ArrayList<>(origSorted.size());
for (List<String> inner : origSorted) {
copySorted.add(new ArrayList<>(inner));
}
CodePudding user response:
Firstly you creat your ArrayList then creat your new arrayList by using the keyWord "new" so the new arraylist will be a new object seprate from the first arraylist like this:
ArrayList<String> myFirstArrayList = new ArrayList<>();//creat my first arrayList
//add some objects
myFirstArrayList.add("1");
myFirstArrayList.add("2");
myFirstArrayList.add("3");
//print it
System.out.println(myFirstArrayList);//[1, 2, 3]
//creating a new arrayList by coping the first but we create a new arrayList by using the keyword "New"
ArrayList<String> newArrayList= new ArrayList<>(myFirstArrayList);
//print new arraylist
System.out.println(newArrayList);//[1, 2, 3]
//make some change in the new arraylist
newArrayList.remove(1);
//print the
System.out.println(newArrayList);//[1, 3]
System.out.println(myFirstArrayList);//[1, 2, 3]
//my original arraylist still not changed b'z the two objects of arraylists are seperate.