gpt4 book ai didi

java - 将一个 ArrayList 添加到另一个 ArrayList

转载 作者:行者123 更新时间:2023-12-01 12:24:38 25 4
gpt4 key购买 nike

我目前正在学习Java Programmer 1 证书,下面的代码是关于将 ArrayList 添加到另一个列表中的。

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

这就是作者所说的:

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.

作者想表达什么?我对他提到的两个案例有点困惑!

任何帮助将不胜感激。

最佳答案

我想我知道作者想说什么。但字符串是一个不好的例子。想象一下这样的事情。他正在解释将类的两个不同实例添加到列表中或将同一实例添加到两个列表中之间的区别。当您将同一实例添加到两个列表时,如果您修改该实例,则更改会反射(reflect)在两个列表中。

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

}

关于java - 将一个 ArrayList 添加到另一个 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26455116/

25 4 0