在Java中,我们可以使用将数组转换为List(ArrayList或LinkedList),步骤如下:
- 循环(for/while/do-while)
- java.util.Arrays.asList()
- java.util.Collections.addAll()
文件:ArrayToListExample.java –
package com.yiibai.tutorial; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * @author * */ public class ArrayToListExample { public static void main(String[] args) { /* Array of integers to be converted */ Integer[] numbers=new Integer[]{546910287}; /* Method - 1 */ List<Integer> numberList1=new ArrayList<>(); for (Integer integer : numbers) { numberList1.add(integer); } System.out.println("Number List1="+numberList1); /* Method - 2 */ List<Integer> numberList2=Arrays.asList(numbers); System.out.println("Number List2="+numberList2); // numberList2.add(20); // This line will throw an exception. /* Method - 3 */ List<Integer> numberList3=new ArrayList<>(); Collections.addAll(numberList3 numbers); System.out.println("Number List3="+numberList3); } }
执行上面示例代码,得到以下结果 –
Number List1=[5 4 6 9 10 2 8 7] Number List2=[5 4 6 9 10 2 8 7] Number List3=[5 4 6 9 10 2 8 7]
java.util.Arrays.asList()
– 此方法返回由指定数组支持的固定大小列表,即无法向列表中添加更多元素,否则程序将抛出异常 –
Exception in thread "main" java.lang.UnsupportedOperationException at java.util.AbstractList.add(Unknown Source) at java.util.AbstractList.add(Unknown Source) ....
要避免上述异常,请将代码更改为:
List<Integer> numberList2=new ArrayList<>(Arrays.asList(numbers));
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264150.html