Sometimes it is needed to convert a Java array to List or Collection because the latter is a more powerful data structure - A java.util.List have many functionality that ordinary array do not support. For example, we can easily check if a List contains a specific value with just one built-in method call. Below are some examples on how to convert an array to List.

Convert Array To List using java.util.Arrays.asList()

The class java.util.Arrays has a convenient method named asList that can help with the task of conversion. Here is the syntax:

public static <T> List<T> asList(T... a)

Notice that the parameter does not necessarily receive an array but varargs. It means we can create a List using this code:

public class Test {
public static void main(String[] args) {
List<String> myList = Arrays.asList("Apple");
}
}

Which creates a List with one item - the String "Apple". We could also do this:

public class Test {
public static void main(String[] args) {
List<String> myList = Arrays.asList("Apple", "Orange");
}
}

This will create a List with two items - the Strings "Apple" and "Orange".

Since this is varargs, we can pass an Array and the items are treated as the arguments. Here is an example code:

public class Test {
public static void main(String[] args) {
String[] myArray = { "Apple", "Banana", "Orange" };
List<String> myList = Arrays.asList(myArray);
for (String str : myList) {
System.out.println(str);
}
}
}

Here, a List of String was created and the contents of the Array "myArray" was added to it. The List "myList" will have the size of 3. Here is the output of the code:

Apple
Banana
Orange

Pitfalls

This approach however has some problems:

  • The Array passed must be an array of Objects and not of primitive type

    If we will pass an array of primitive type, for example:

    public class Test {
    public static void main(String[] args) {
    int[] myArray = { 1, 2, 3 };
    List myList = Arrays.asList(myArray);
    System.out.println(myList.size());
    }
    }

    The output of the code will be:

    1
    

    Why? Because the asList method is expecting a varargs of Objects and the parameters passed is an Array of primitive, what it did was it created a List of Array! And the only element of the List is "myArray". Hence, this code

    myList.get(0)
    

    will return the same object as "myArray".

  • The List created by asList is fixed-size

    The returned list by the asList method is fixed sized and it can not accommodate more items. For example:

    public class Test {
    public static void main(String[] args) {
    String[] myArray = { "Apple", "Banana", "Orange" };
    List<String> myList = Arrays.asList(myArray);
    myList.add("Guava");
    }
    }

    Will have the output:

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

    Because myList is fixed-sized an can't add more items to it.

Convert Primitive Array To List

As mentioned above, passing a primitive array to Arrays.asList() will
not work. A workaround without introducing a third party library is
through Java 8's stream. Here is an example:

public class Test {
public static void main(String[] args) {
int[] intArray = { 5, 10, 21 };
List myList = Arrays.stream(intArray).boxed()
.collect(Collectors.toList());
}
}

And the individual array items will be converted from int to Integer (boxing), and converted to a List.

Convert Array To List That Allows Adding More Items

As mentioned in pitfalls above, the result of Arrays.asList() does not
support adding or removing items. If you don't want this behavior, here
is an alternative solution:

public class Test {
public static void main(String[] args) {
String[] myArray = { "Apple", "Banana", "Orange" };
List<String> myList = new ArrayList<String>(Arrays.asList(myArray));
myList.add("Guava");
}
}

What this code do is create a new ArrayList explicitly and then add the items from the result of Arrays.asList(). And since it is our code that created the ArrayList, there is no restriction in adding or removing items. The code above will have 4 items in it right before the program ends. No exception will be thrown when the code is executed.

Convert Array To List Using Own Implementation

There are times when it is better to use our own implementation when
solving a problem. Here is a simple implementation of converting a Java
array to List:

public class Test {
public static void main(String[] args) {
String[] myArray = { "Apple", "Banana", "Orange" };
List<String> myList = new ArrayList<String>();
for (String str : myArray) {
myList.add(str);
}
System.out.println(myList.size());
}
}

The expected output of the code is that it should display "3", because there are 3 items in the List after the logic is executed.

The downside of this is that our code is longer and we are reinventing the wheel. The pros is that we can accommodate customization if our requirement changes. For example, here is the code where each item in the array is added twice to the List.

public class Test {
public static void main(String[] args) {
String[] myArray = { "Apple", "Banana", "Orange" };
List<String> myList = new ArrayList<String>();
for (String str : myArray) {
myList.add(str);
myList.add(str);
}
System.out.println(myList.size());
}
}

Here the output becomes 6 because each String in the array was added twice. Here is another example that converts an array of String to a List of Integer:

public class Test {
public static void main(String[] args) {
String[] myArray = { "5", "6", "7" };
List<Integer> myList = new ArrayList<Integer>();
for (String str : myArray) {
myList.add(Integer.valueOf(str));
}
}
}

Each String in the array is parsed and converted to corresponding Integer. The resulting List will contain all converted Integers.

Arrays.asList() 的使用注意的更多相关文章

  1. 【转】java.util.Arrays.asList 的用法

    DK 1.4对java.util.Arrays.asList的定义,函数参数是Object[].所以,在1.4中asList()并不支持基本类型的数组作参数. JDK 1.5中,java.util.A ...

  2. Arrays.asList()注意

    api: public static <T> List<T> asList(T... a) 返回一个受指定数组支持的固定大小的列表.(对返回列表的更改会“直接写”到数组.)此方 ...

  3. Arrays.toString Arrays.asList

    import java.util.Arrays; public class TestCalc{ public static void main(String[] args) { ,,,,,,,}; / ...

  4. Arrays.asList()使用注意点

    今天看代码时, 发现书上使用了Arrays.asList()方法, 将一个数组转成了List, 然后说到得到的List不能调用add(), remove()方法添加元素或者删除,带着疑问看了下内部实现 ...

  5. Arrays.asList(数组) 解说

    最近在用Arrays的asList()生成的List时,List元素的个数时而不正确. Java代码 一:Arrays.asList(数组)该方法是将数组转化为集合(该方法主要用于Object对象数组 ...

  6. Arrays.asList方法总结

    import java.util.Arrays; import java.util.List; /** * * 本类演示了Arrays类中的asList方法 * 通过四个段落来演示,体现出了该方法的相 ...

  7. Arrays.asList的使用及异常问题

    将数组转成List问题,通常我们习惯这样写成:List<String> list = Arrays.asList("1","2"); 于是我们这样就 ...

  8. Arrays.asList引起的惨案

    最近代码中需要对两个数组求交,想当然便用到了List中的retainAll函数,但要将将数组转换成list.代码如下: String[] abc = new String[] { "abc& ...

  9. Arrays.asList的源码分析

    以前一直很奇怪为什么Arrays.asList的数组不能插入新的数据,后来看了源码发现是因为内部是一个final的数组支持起来的Arraylist,下面贴入源码与分析. 1.先看Arrays的方法 我 ...

  10. 【转载】最近在用Arrays的asList()生成的List时,List元素的个数时而不正确,数组转化为List,即Arrays.asList(intArray);

    最近在用Arrays的asList()生成的List时,List元素的个数时而不正确. Java代码 //经多次测试,只要传递的基本类型的数组,生成List的元素个数均为1 char arrc = { ...

随机推荐

  1. HDU1542-Atlantis【离散化&线段树&扫描线】个人认为很全面的详解

    刚上大一的时候见过这种题,感觉好牛逼哇,这都能算 如今已经不打了,不过适当写写题保持思维活跃度还是不错的,又碰到这种题了,想把它弄出来 说实话,智商不够,看了很多解析,花了4.5个小时才弄明白 网上好 ...

  2. zookeeper部署

    版本:zookeeper-3.4.5-cdh5.10.0.tar.gz 网址:http://archive-primary.cloudera.com/cdh5/cdh/5/ 1. 解压 $ tar - ...

  3. Python学习day4 数据类型Ⅱ(列表,元祖)

    day4 知识补充&数据类型:列表,元祖 1.知识补充 1.编译型/解释型 编译型:在代码编写完成之后编译器将其变成另外一个文件教给你算计执行. 代表语言:Java,c,c++ ,c#, Go ...

  4. Spring Cloud下基于OAUTH2认证授权的实现

    GitHub(spring -boot 2.0.0):https://github.com/bigben0123/uaa-zuul 示例(spring -boot 2.0.0): https://gi ...

  5. 【CH6901】骑士放置

    题目大意:给定一个 N*M 的棋盘,有一些格子禁止放棋子.问棋盘上最多能放多少个不能互相攻击的骑士(国际象棋的"骑士",类似于中国象棋的"马",按照" ...

  6. (六)Oracle 的 oracle表查询关键字

    参考:http://www.hechaku.com/Oracle/oracle_tables2.html 1.使用逻辑操作符号问题:查询工资高于500或者是岗位为manager的雇员,同时还要满足他们 ...

  7. 腾讯云centos7安装MySQL

    centos就centos呗,为什么要加个腾讯云呢?有这种疑问的兄dei,一定是没被不同云的系统坑过啊,阿里云的Ubuntu和腾讯云的Ubuntu不一样,centos好像也有差别,各个云平台,同样的系 ...

  8. bzoj1791[IOI2008]Island岛屿(基环树+DP)

    题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=1791 题目大意:给你一棵n条边的基环树森林,要你求出所有基环树/树的直径之和.n< ...

  9. 你真的知道什么是【共享Session】,什么是【单点登录】吗?

    一直有人问,为什么我实现的共享session不能单点登录,今天我也抽时间准备好好说一下. 我要喷(别喷我) 首先,网上水货文章很多,CSDN居多.CSDN转载率很高,也就是说同相同文章有很多,换汤不换 ...

  10. 记cccc天梯赛第三届决赛

        首先我很想知道,为什么我没有参加初赛,就可以去决赛,这个究竟有没有初赛,这真是未解之谜.     其次,会长说得不错,菜是原罪.不知道这次的表现能不能把我送去湘潭挑战赛....     我身边 ...