Java数组到列表(ArrayList)的转换
时间:2020-02-23 14:36:21 来源:igfitidea点击:
有时我们需要在Java中将Array转换为List,在这里我们将学习两种不同的方法来实现这一点。
由于List是接口,而ArrayList是最受欢迎的实现,因此它与将Array转换为ArrayList相同。
当您调用某些第三方类返回一个数组,然后需要将它们更改为列表,或者向列表中添加更多数据时,就会出现这种情况。
列出的Java数组
在Java中,有两种内置方法可以将Array转换为List。
Arrays.asList(T…a):这是在Java中将Array转换为ArrayList的最简单方法,但是此方法以ArrayList的形式返回数组的基础表示形式。
返回的ArrayList是固定大小的,任何修改尝试都会在运行时导致UnsupportedOperationException。
同样,数组中的任何更改也将更改ArrayList中的元素。Collections.addAll(ArrayList <T> strList,T [] strArr):这是将数组转换为ArrayList的最佳方法,因为数组数据已复制到列表,并且两者都是独立的对象。
复制数组后,您可以独立修改两个对象。
集合是Java Collections Framework中非常有用的类,它提供了许多实用程序方法。
现在,让我们看看这两种方法的实际作用。
package com.theitroad.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"};
List<String> strList = new ArrayList<String>();
//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<String>();
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);
}
}
上面程序的输出是:
Original ArrayList from Arrays.asList() 1 2 3 4 Change in array effect on ArrayList 5 2 3 4 Array to ArrayList using Collections.addAll() 5 2 3 4 5

