kmugi
kmugi

Reputation: 363

Problems with copying and modifying a clone of another ArrayList<Integer> java

I have an ArrayList that I want to clone and hence I made the following:

import java.util.ArrayList;
import java.util.Arrays;

public class Test {
    public static ArrayList<ArrayList<Integer>> answer = new ArrayList<ArrayList<Integer>>();
    public static ArrayList<ArrayList<Integer>> copans = new ArrayList<ArrayList<Integer>>();

    public static void main(String[] args) {
        ArrayList<Integer> yolo = new ArrayList<Integer>();
        yolo.add(9);
        yolo.add(0);
        yolo.add(1);
        answer.add(yolo);
        appendRow();
    }

    static void appendRow() {
        copans.addAll(answer);
        copans.get(0).remove(0);
        copans.get(0).remove(0);
        System.out.println("ans "+answer);
    }
}

appendRow() would result in copans becoming [1] from previously [9, 0, 1]. However, I did not expect that answer would become [1] as well instead of [9, 0, 1], which does not make sense at all.

I was wondering if I did not copy the values in the correct way? Thanks for your help!

Upvotes: 1

Views: 44

Answers (1)

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17132

You probably meant:

public static ArrayList<Integer> answer = new ArrayList<Integer>();
public static ArrayList<Integer> copans = new ArrayList<Integer>();

public static void main(String[] args) {
    answer.add(9);
    answer.add(0);
    answer.add(1);
    appendRow();
}

static void appendRow() {
    copans.addAll(answer);
    copans.remove(0);
    copans.remove(0);
    System.out.println("answer: "+answer);
    System.out.println("copans: "+copans);
}

Output:

answer: [9, 0, 1]
copans: [1]

The copy & removal of elements work just fine.

EDIT:

Still after you updated your question, your code won't compile since the yolo arrayList is accessible only in the main method.

Upvotes: 5

Related Questions