简体   繁体   English

java ArrayList克隆几次

[英]java ArrayList clone several times

I am trying to clone my ArrayList 4 times using a for-loop and clone() method, but I could not. 我正在尝试使用for-loopclone()方法将我的ArrayList克隆4次,但是我做不到。 The below is the (straightforward) code I wrote: 以下是我编写的(直接)代码:

static ArrayList<Integer> newArrList;
    for (int n = 1; n <= 4; n++) {
        ArrayList<Integer> arrList = new ArrayList<>();
        for (int i = 1; i <= 13; i++) {
            arrList.add(i);
        }
        newArrList = (ArrayList<Integer>) arrList.clone();
        for (int i = 1; i <= 13; i++) {
            newArrList.add(i);
        }
    }

The output is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] It prints my arrList only 2 times, but I want it 4 times. 输出为: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]它仅打印我的arrList 2次,但我希望它打印4次。 Like that: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] 像这样: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

Is it the best way to clone an ArrayList multiple times? 是多次克隆ArrayList的最佳方法吗? and what am I doing wrong? 我在做什么错?

Your code seems a little too confusing to me, so I'm unable to point out where exactly you went wrong. 您的代码对我来说似乎有点令人困惑,因此我无法指出您到底出了错。

The first thing I don't understand is why you create your test list 4 times (inside the main loop). 我不明白的第一件事是为什么要创建4次测试列表(在主循环内)。 Shouldn't it be created just once? 它不应该创建一次吗?

Then doing a clone and adding the 13 elements afterwards put the content twice in the new list. 然后进行clone ,然后添加13个元素,将内容两次放入新列表中。 Once as a copy of the original content, and then as hard-coded data. 一次作为原始内容的副本,然后作为硬编码的数据。 I don't understand the motivation behind that. 我不明白其背后的动机。

Anyway, I would just create a new (empty) list and add all the elements of the original list 4 times using addAll : 无论如何,我只会创建一个新的(空)列表,并使用addAll将原始列表的所有元素添加4次:

// create test list
ArrayList<Integer> arrList = new ArrayList<>();
for (int i = 1; i <= 13; i++) {
    arrList.add(i);
}

// clone
ArrayList<Integer> newArrList = new ArrayList<>();
for (int i = 0; i < 4; i++) {
    newArrList.addAll(arrList);
}

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

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