为什么当我打电话
ArrayList<String> reversedList = ListUtils.reverse(list);
正在修改原始列表,即使我在方法中制作了它的副本
package com.javablackbelt.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ListUtils {
public static void main(String arg[]) {
String[] arr = {"one", "two", "three", "four", "five"};
ArrayUtils.print(arr);
System.out.println();
String [] reversedArr = ArrayUtils.reverse(arr);
ArrayUtils.print(reversedArr);
System.out.println();
ArrayList<String> list = ArrayUtils.toArrayList(arr);
ListUtils.print(list);
ArrayList<String> reversedList = ListUtils.reverse(list);
ListUtils.print(reversedList);
String[] arrFromList = ListUtils.toArray(list);
ArrayUtils.print(arrFromList);
}
public static void print(ArrayList<String> aStr) {
System.out.print("list: [ ");
for(String l: aStr)
System.out.print(l+" ");
System.out.println(" ] size: "+aStr.size());
}
public static ArrayList<String> reverse(ArrayList<String> aList) {
ArrayList<String> newList = aList;
Collections.reverse(newList);
return newList;
}
public static String[] toArray(ArrayList<String> list) {
ArrayList<String> newList = list;
String[] newStr = newList.toArray(new String[list.size()]);
return newStr;
}
}