問題 一:
代碼如下:
int [] arr = new int[5];
arr[0]=1;
arr[1]=2;
arr[2]=3;
arr[3]=4;
arr[4]=5;
List<int[]> list = Arrays.asList(arr);
list.remove(0);
運行後 :
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:144)
at test.testArr23.main(testArr23.java:18)
原因分析
Arrays.asList 返回的List類型爲 Arrays 的內部類的類型 : private static class ArrayList<E> extends AbstractList<E>
只是 最簡 實現的接口和抽象類,導致AbstractList<E> 中未抽象方法 拋出異常<span style="font-family: Arial, Helvetica, sans-serif;">UnsupportedOperationException</span>.
類似如下:
<pre name="code" class="html"> public E set(int index, E element) {
<span style="white-space:pre"> </span>throw new UnsupportedOperationException();
}
public void add(int index, E element) {
<span style="white-space:pre"> </span>throw new UnsupportedOperationException();
}
public E remove(int index) {
<span style="white-space:pre"> </span>throw new UnsupportedOperationException();
}
</pre><pre name="code" class="html">問題 一:
代碼如下:
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
String[] strArr = new String[3];
strArr[0] = "11";
strArr[1] = "22";
strArr[2] = "33";
<h2> <span style="font-family:SimHei;"> List<String> strlist = Arrays.asList(strArr);
List<int[]> arrlist = Arrays.asList(arr);
</span><span style="font-family:SimHei;"> </span></h2> for (String j : strlist)
{
System.out.println(j);
}
for (int j : arrlist.get(0))
{
System.out.println(j);
}