欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Arrays.asList 分析 博客分类: Java Java 

程序员文章站 2024-03-24 10:16:52
...

问题 一:

代码如下:

 

    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);
    }

 


 

相关标签: Java