2018-7-6 java数组转list

java数组转list   

java中数组转list使用Arrays.asList(T... a)方法。

示例:

1
2
3
4
5
6
7
8
9
10
public  class  App {
   public  static  void  main(String[] args) {
     List<String> stringA = Arrays.asList( "hello" "world" , "A" );
     String[] stringArray = { "hello" , "world" , "B" };
     List<String> stringB = Arrays.asList(stringArray);
 
     System.out.println(stringA);
     System.out.println(stringB);
   }
}

 运行结果:

1
2
[hello, world, A]
[hello, world, B]

 这个方法使用起来非常方便,简单易懂。但是需要注意以下两点。

一、不能把基本数据类型转化为列表

仔细观察可以发现asList接受的参数是一个泛型的变长参数,而基本数据类型是无法泛型化的,如下所示:

1
2
3
4
5
6
7
8
9
10
11
public  class  App {
   public  static  void  main(String[] args) {
     int [] intarray = { 1 2 3 4 5 };
     //List<Integer> list = Arrays.asList(intarray); 编译通不过
     List< int []> list = Arrays.asList(intarray);
     System.out.println(list);
   }
}
 
output:
[[I @66d3c617 ]

这是因为把int类型的数组当参数了,所以转换后的列表就只包含一个int[]元素。

解决方案:

  要想把基本数据类型的数组转化为其包装类型的list,可以使用guava类库的工具方法,示例如下:

扫描二维码关注公众号,回复: 2178865 查看本文章
1
2
int [] intArray = { 1 2 3 4 };
List<Integer> list = Ints.asList(intArray);

 

 二、asList方法返回的是数组的一个视图

视图意味着,对这个list的操作都会反映在原数组上,而且这个list是定长的,不支持add、remove等改变长度的方法。

1
2
3
4
5
6
7
8
9
10
11
public  class  App {
   public  static  void  main(String[] args) {
     int [] intArray = { 1 2 3 4 };
     List<Integer> list = Ints.asList(intArray);
     list.set( 0 100 );
     System.out.println(Arrays.toString(intArray));
     list.add( 5 );
     list.remove( 0 );
 
   }
}

 output:

1
2
3
[ 100 2 3 4 ]
UnsupportedOperationException
UnsupportedOperationException

猜你喜欢

转载自blog.csdn.net/fly_captain/article/details/80936614
今日推荐