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.

最新文章

  1. CC2540自己的配置文件
  2. 用SSH登录局域网中使用网络设置为NAT的虚拟机中的linux
  3. 单例(Singleton pattern)模式的七种写法
  4. css 中的度量单位
  5. dtd语法之定义属性
  6. matlab 相关代码记录
  7. window下安装composer和laravel
  8. Getting Started with the NDK
  9. windows进程间通讯的方法
  10. pads&#160;layout 自动打地孔
  11. k8s Docker私有仓库认证
  12. 分库分表之后全局id怎么生成
  13. TCP/UDP OSI_layer 4
  14. js_倒计时去执行函数或则跳转页面
  15. vscode 正则 计算代码全部有效行数;清除文件空行
  16. 03-03 java 顺序语句结构,选择结构if语句
  17. PLSQL_统计信息系列01_统计信息的概念和重要性
  18. Mac之安装zsh
  19. waitpid()设置WNOHANG位(非阻塞模式)判断子进程的状态是否有所改变
  20. iOS: 使用故事板和xib设置按钮圆角方法

热门文章

  1. jsp配置
  2. yarn如何全局安装命令以及和环境变量的关系
  3. python学习日记(深浅copy)
  4. Android 可展开列表组件 ExpandableListView
  5. NOIP2017逛公园(dp+最短路)
  6. 从Java的角度简单修复Cookie越权漏洞
  7. BZOJ 4562: [Haoi2016]食物链(拓扑排序)
  8. 上pixiv解决法(保存)
  9. 洛谷P4242 树上的毒瘤
  10. .Net Core Nlog日志记录到MySql