有两个ArrayList例如list1 = {1,2,3} 和list2 = {7,6,4,2}如何交换这两个列表.结果将是list1 = {7,6,4,2},list2 = {1,2,3}
我可以像这样实现:
public void swapList(ArrayList<Integer> list1, ArrayList<Integer> list2){
ArrayList<Integer> tmpList = list1;
list1 = list2;
list2 = tmpList;
}
Run Code Online (Sandbox Code Playgroud)
And*_*s_D 12
不,你不能这样实现它.与数组相同.像其他人已经解释的那样,传递参考价值问题.
如果您希望列表交换其内容,则必须清除并复制:
public static void swapList(List<Integer> list1, List<Integer> list2){
List<Integer> tmpList = new ArrayList<Integer>(list1);
list1.clear();
list1.addAll(list2);
list2.clear();
list2.addAll(tmpList);
}
Run Code Online (Sandbox Code Playgroud)
一些额外的想法:
List<Integer> list1 = getList1Magic();
List<Integer> list2 = getList2Magic();
if (isSwapReferences()) {
// this does not affect the actual lists
List<Integer> temp = list2;
list2 = list1;
list1 = temp;
} else if (isSwapListContent()) {
// this modifies the lists
swapList(list1, list2); // method from above
}
Run Code Online (Sandbox Code Playgroud)
交换策略取决于您的要求.第一个块具有局部效果,第二个块具有全局效果.
| 归档时间: |
|
| 查看次数: |
7181 次 |
| 最近记录: |