Gary Fox
Gary Fox

Reputation: 141

Adding An ArrayList To Another ArrayList

I am currently studying for the Java Programmer 1 certificate and the following piece of code came up about adding an ArrayList to another.

ArrayList<String> myArrList = new ArrayList<String>();
            myArrList.add("One");
            myArrList.add("Two");
            ArrayList<String> yourArrList = new ArrayList<String>();
            yourArrList.add("Three");
            yourArrList.add("Four");
            myArrList.addAll(1, yourArrList); 
            for (String val : myArrList)
             System.out.println(val);

This is what the author then says:

What happens if you modify the common object references in these lists, myArrList and yourArrList? We have two cases here:

In the first one, you reassign the object reference using either of the lists. In this case, the value in the second list will remain unchanged.

In the second case, you modify the internals of any of the common list elements,in this case, the change will be reflected in both of the lists.

What is the author trying to say?? I am a bit confused about the 2 cases he mentions!

Any help would be greatly appreciated.

Upvotes: 0

Views: 200

Answers (1)

m32rober
m32rober

Reputation: 151

I think I know what the author is trying to say. But Strings are a bad example to do it with. Imagine something like this. He is explaining the difference between adding two different instances of a class to the lists, or adding the same instance to both lists. When you add the same instance to both lists, if you modify that instance the change is reflected in both lists.

import java.util.ArrayList;

public class Example {

    private static class Node {
        private int value;

        public Node(final int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }

        public void setValue(final int value) {
            this.value = value;
        }
    }

    public static void main(final String... args) {
        final ArrayList<Node> nodes1 = new ArrayList<>();
        final ArrayList<Node> nodes2 = new ArrayList<>();

        // add two different Node objects that happen to have same value
        nodes1.add(new Node(1337));
        nodes2.add(new Node(1337));

        Node node = new Node(69);

        // add the same node to both lists
        nodes1.add(node);
        nodes2.add(node);

        node.setValue(420);

        // do your join here and print result to see {1337, 420, 1337, 420}
        nodes1.addAll(0, nodes2);
        for (final Node n : nodes1)
            System.out.println(n.getValue());
    }

}

Upvotes: 1

Related Questions