0

So, I have this use case:

ArrayList<String> test1 = new ArrayList<String>();
test1.add("string1");
test1.add("string2");

ArrayList<String> test2 = test1;
test2.remove(0);
System.out.println(test1.get(0)); // Expect to see "string1"

The first ArrayList test1, has two String elements. Then I make a new (?) ArrayList, test2, which is the same as test1. When I remove the first element from test2 (which is "string1") and then try to display the first element from test1, it returns "string2"... also there the first element "string1" is removed somehow.

How is that possible?

1
  • 6
    you're using the same instance of the arraylist in both variables Commented May 24, 2017 at 16:49

4 Answers 4

1

Then I make a new (?) ArrayList, test2, which is the same as test1.

No you haven't. You have just pointed your arraylist 2 to arraylist 1.

You can either use a Shallow constructor of list or use addAll method.

List<String> test2 = new ArrayList<String>();
test2.addAll(test1);
Sign up to request clarification or add additional context in comments.

Comments

0

You are assigning the reference of test1 to test2. This means, that both the ArrayList refer to the same instance,

Therefore, methods called on one, will virtually reflect in the other one too, as they refer to the same object.

To achieve what you want, do

List<String> test2 = new ArrayList<>(test1);

This copies the contents of the test1 to test2.

Comments

0

Create a new ArrayList with the same elements as test1

ArrayList<String> test2 = new ArrayList<>(test1)

1 Comment

Why not just ArrayList<String> test2 = new ArrayList<>(test1)? What do you think Arrays.asList() adds to the picture?
0
    ArrayList<String> test1 = new ArrayList<String>();
    test1.add("string1");
    test1.add("string2");

    ArrayList<String> test2 = test1;
    test2.remove(0);
    System.out.println(test1.get(0)); // Expect to see "string1"

    ArrayList<String> test3 = new ArrayList<>();

Upon running the code in debug you can see that the reference of test1 and test2 is pointing to the same location. That is because you are not copying the values but assigning the same reference to the other list. Notice that the reference of test3 is different than the other 2.

In order to just copy the values you can use

test2 = new ArrayList<Object>(test1);

Please find the image attached below to view the reference value.

Result of running the code stated above in debug

Comments

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.