简体   繁体   中英

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

Is it the best way to clone an ArrayList multiple times? 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). 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. 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 :

// 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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