简体   繁体   English

ArrayList 的复制构造函数<arraylist<string> &gt; 不工作 Java </arraylist<string>

[英]Copy constructor of ArrayList<ArrayList<String>> not Working Java

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.我希望在不引用原始文件的情况下生成 origSorted 的副本,但是每当我对 copySorted 进行更改时,它最终也会发生在 origSorted 上。 I also tried the.clone() function with the same results.我还尝试了 the.clone() function,结果相同。

It's not the changes to copySorted you're seeing, it's changes to the inner lists which are shared between the outer lists.您看到的不是对copySorted的更改,而是对在外部列表之间共享的内部列表的更改。 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));
}

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: 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM