1

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!

2
  • 2
    Your code does not even compile. Commented Dec 15, 2015 at 11:17
  • Hey Sparta, thanks for pointing that out, I forgot to add an ArrayList<Integer> to answer. Now it is corrected and, as asked, it removes both the original and the copied array list values. Commented Dec 15, 2015 at 11:25

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It compiles fine on mine
@KevinMugianto No it doesn't
Lol sorry guys forgot to delete the last System.out.println(yolo); Should work now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.