以下是抛出strList5的subList.clear()调用异常的代码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public static List<String> removeRange(List<String> strList, int maxElementsToBeAllowedInList) {
if (strList.size() > maxElementsToBeAllowedInList) {
System.out.println("Clearing out sublist: ["
+ strList.subList(maxElementsToBeAllowedInList, strList.size()) + "]");
strList.subList(maxElementsToBeAllowedInList, strList.size()).clear();
}
return strList;
}
public static void main(String[] args) {
List<String> strList1 = new ArrayList<>();
List<String> strList2 = Arrays.asList("one", "two", "three");
List<String> strList3 = Arrays.asList("one", "two", "three", "four", "five");
List<String> strList4 = Arrays.asList("one", "two", "three", "four", "five", "six");
List<String> strList5 = Arrays.asList("one", "two", "three", "four", "five", "six", "seven", "eight");
try {
System.out.println("Before modification strList1: [" + strList1 + "]");
ListTruncateEndTest.removeRange(strList1, 5);
System.out.println("After modification strList1: [" + strList1 + "]");
System.out.println("Before modification strList2: [" + strList2 + "]");
ListTruncateEndTest.removeRange(strList2, 5);
System.out.println("After modification strList1: [" + strList2 + "]");
System.out.println("Before modification strList3: [" + strList3 + "]");
ListTruncateEndTest.removeRange(strList3, 5);
System.out.println("After modification strList1: [" + strList3 + "]");
System.out.println("Before modification strList4: [" + strList4 + "]");
ListTruncateEndTest.removeRange(strList4, 5);
System.out.println("After modification strList4: [" + strList4 + "]");
System.out.println("Before modification strList5: [" + strList5 + "]");
ListTruncateEndTest.removeRange(strList5, 5);
System.out.println("After modification strList5: [" + strList5 + "]");
} catch (Exception e) {
System.out.println("Error: [" + e.toString() + "]");
}
}
Before modification strList1: [[]]
After modification strList1: [[]]
Before modification strList2: [[one, two, three]]
After modification strList2: [[one, two, three]]
Before modification strList3: [[one, two, three, four, five]]
After modification strList3: [[one, two, three, four, five]]
Before modification strList4: [[one, two, three, four, five, six]]
Clearing out sublist: [[six]]
Error: [java.lang.UnsupportedOperationException]
我如何清除子列表有什么问题吗?或者这是Java 8中的Bug? 我在Mac上的Java 8版本是: java版&#34; 1.8.0_45&#34; Java(TM)SE运行时环境(版本1.8.0_45-b14) Java HotSpot(TM)64位服务器VM(版本25.45-b02,混合模式)
答案 0 :(得分:3)
Arrays.asList
返回的列表是固定长度的,因此在clear
上调用subList
会引发UnsupportedOperationException
。
您需要改为使用ArrayList
。
List<String> strList2 = new ArrayList<>(Arrays.asList("one", "two", "three"));