Arrays.asList使用注意

来源:互联网 发布:多益网络加班严重吗 编辑:程序博客网 时间:2024/05/18 12:36

当传入的是基本类型时,会把传过来的数组作为list的第一个元素:

[java] view plain copy
  1. public class ArraysasList {  
  2.   
  3.     public static void main(String[] args) {  
  4.         int[] a = {1,2,3,4,8,10,22,12,214,23};  
  5.         String[] b = {"a","b","c"};  
  6.         Integer[] c = {1,2,3,4,8,10,22,12,214,23};  
  7.         System.out.println(a);  
  8.         System.out.println(Arrays.asList(b));  
  9.         System.out.println(Arrays.asList(c));  
  10.     }  
  11.   
  12. }  

输出结果:

[I@179935d
[a, b, c]
[1, 2, 3, 4, 8, 10, 22, 12, 214, 23]


Arrays第二个问题,在添加或者删除的时候会报错:

[java] view plain copy
  1. public class ArraysasList {  
  2.   
  3.     public static void main(String[] args) {  
  4.         int[] a = {1,2,3,4,8,10,22,12,214,23};  
  5.         String[] b = {"a","b","c"};  
  6.         Integer[] c = {1,2,3,4,8,10,22,12,214,23};  
  7.         System.out.println(a);  
  8.         System.out.println(Arrays.asList(b));  
  9.         System.out.println(Arrays.asList(c));  
  10.           
  11.         List<String> bList = Arrays.asList(b);  
  12.         bList.add("d");  
  13.         System.out.println(bList);  
  14.     }  
  15. }  

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(AbstractList.java:148)
    at java.util.AbstractList.add(AbstractList.java:108)
    at ArraysasList.main(ArraysasList.java:16)

源码中写到:

public void add(int index, E element) {
07    throw new UnsupportedOperationException();
08}
09   
10public E remove(int index) {
11    throw new UnsupportedOperationException();
12}
原创粉丝点击