import java.util.*;
public class Metodo {
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList();
a.add(1);
a.add(2);
a.add(3);
a.add(4);
a.add(5);
Metodo.inverte(a);
for(int i=0; i<a.size(); i++) {
System.out.println(a.get(i));
}
}
public static void inverte(ArrayList<Integer> a) {
ArrayList<Integer> other = new ArrayList();
other = a;
for(int i=0; i<a.size(); i++) {
a.set(i, other.get(other.size()-i-1));
}
}
}
Run Code Online (Sandbox Code Playgroud)
此方法应该反转ArrayList中的数字,因此它应该打印"5 4 3 2 1",但它打印"5 4 3 4 5"而不是.为什么?
other = a;
Run Code Online (Sandbox Code Playgroud)
并没有创造原件及复印件List.
双方a并other引用相同的List对象,所以当你打电话a.set(0,other.get(other.size()-1),你失去了原来的价值other.get(0).
你应该使用:
ArrayList<Integer> other = new ArrayList<>(a);
Run Code Online (Sandbox Code Playgroud)
创建原始副本List并删除other = a;
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |