本文共 3739 字,大约阅读时间需要 12 分钟。
Sometimes we need to convert Array to List in java, here we will learn two different ways to achieve this. Since List is an interface and ArrayList is the most popular implementation, it’s the same as converting an Array to ArrayList. This situation can come when you are invoking some third party classes returning an array and then you need to change them to list, or to add some more data to the list.
有时我们需要用Java将Array转换为List ,在这里我们将学习两种不同的方法来实现这一点。 由于List是接口,而ArrayList是最流行的实现,因此它与将Array转换为ArrayList相同。 当您调用某些第三方类返回一个数组,然后需要将它们更改为列表,或向列表中添加更多数据时,可能会出现这种情况。
There are two built-in ways to convert Array to List in Java.
有两种内置方法可以将Java中的Array转换为List。
Now let’s see both these methods usage in action.
现在,让我们看看这两种方法的用法。
package com.journaldev.util;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;public class ArrayToArrayList { /** * This class shows different methods to convert Array to ArrayList * * @param args */ public static void main(String[] args) { String[] strArr = {"1", "2", "3", "4"}; ListstrList = new ArrayList (); //return the list representation of array //any change in array elements will change the arrayList elements also strList = Arrays.asList(strArr); System.out.println("Original ArrayList from Arrays.asList()"); for (String str : strList) System.out.print(" " + str); //change the array element and see the effect is propogated to list also. strArr[0] = "5"; System.out.println("\nChange in array effect on ArrayList"); for (String str : strList) System.out.print(" " + str); //below code will throw java.lang.UnsupportedOperationException because // Arrays.asList() returns a fixed-size list backed by the specified array. //strList.add("5"); strList = new ArrayList (); Collections.addAll(strList, strArr); //change both the array and arraylist and check if they are independent? strList.add("5"); strArr[0] = "1"; System.out.println("\nArray to ArrayList using Collections.addAll()"); for (String str : strList) System.out.print(" " + str); }}
The output of the above program is:
上面程序的输出是:
Original ArrayList from Arrays.asList() 1 2 3 4Change in array effect on ArrayList 5 2 3 4Array to ArrayList using Collections.addAll() 5 2 3 4 5
So now you know which method to use to convert Array to ArrayList based on the requirements.
现在,您知道了根据要求使用哪种方法将Array转换为ArrayList 。
Here is the video tutorial explaining it in Eclipse.
这是在Eclipse中解释它的视频教程。
翻译自:
转载地址:http://xmozd.baihongyu.com/