问题
So the below method I'm aware causes both variables to point to the same object, but if I did want to find the simplest method to has ArrayList s2 exactly the same as s1, how would I do this?
public static void main(String[] args) {
ArrayList<String> s1 = new ArrayList<String>();
for (int i = 1; i <= 3; i++) {
s1.add(""+i);
}
ArrayList<String> s2 = s1;
}
回答1:
You should create s2 with s1 as parameter.
public static void main(String[] args) {
ArrayList<String> s1 = new ArrayList<String>();
for (int i = 1; i <= 3; i++) {
s1.add(""+i);
}
ArrayList<String> s2 = new ArrayList<String>(s1);
}
来源:https://stackoverflow.com/questions/10457302/java-copying-array-list