原文: https://beginnersbook.com/2013/12/how-to-convert-array-to-arraylist-in-java/

在上一个教程中,我们共享了两个使用示例将ArrayList转换为数组的方法。这里我们分享三种不同的方式将数组转换为ArrayList。基本上我们将String数组转换为String类型的ArrayList

String array[] to ArrayList<String>

方法 1:使用Arrays.asList()进行转换

句法:

ArrayList<T> arraylist = new ArrayList<T>(Arrays.asList(arrayname));

例:

在这个例子中,我们使用Arrays.asList)方法将Array转换为ArrayList

  1. import java.util.*;
  2. public class ArrayToArrayList {
  3. public static void main(String[] args) {
  4. /* Array Declaration and initialization*/
  5. String citynames[]={"Agra", "Mysore", "Chandigarh", "Bhopal"};
  6. /*Array to ArrayList conversion*/
  7. ArrayList<String> citylist= new ArrayList<String>(Arrays.asList(citynames));
  8. /*Adding new elements to the converted List*/
  9. citylist.add("New City2");
  10. citylist.add("New City3");
  11. /*Final ArrayList content display using for*/
  12. for (String str: citylist)
  13. {
  14. System.out.println(str);
  15. }
  16. }
  17. }

输出:

  1. Agra
  2. Mysore
  3. Chandigarh
  4. Bhopal
  5. New City2
  6. New City3

方法 2:Collections.addAll方法

Collections.addAll方法将所有数组元素添加到指定的集合中。这就是调用Collections.addAll方法的方法。它与Arrays.asList方法的作用相同,但它比它快得多,因此性能方面这是将数组转换为ArrayList的最佳方法。

  1. String array[]={new Item(1), new Item(2), new Item(3), new Item(4)};
  2. ArrayList&lt;T&gt; arraylist = new ArrayList&lt;T&gt;();
  3. Collections.addAll(arraylist, array);

  1. Collections.addAll(arraylist, new Item(1), new Item(2), new Item(3), new Item(4));

实现示例

  1. import java.util.*;
  2. public class Example2 {
  3. public static void main(String[] args) {
  4. /* Array Declaration and initialization*/
  5. String array[]={"Hi", "Hello", "Howdy", "Bye"};
  6. /*ArrayList declaration*/
  7. ArrayList<String> arraylist= new ArrayList<String>();
  8. /*Conversion*/
  9. Collections.addAll(arraylist, array);
  10. /*Adding new elements to the converted List*/
  11. arraylist.add("String1");
  12. arraylist.add("String2");
  13. /*Display array list*/
  14. for (String str: arraylist)
  15. {
  16. System.out.println(str);
  17. }
  18. }
  19. }

结果:

  1. Hi
  2. Hello
  3. Howdy
  4. Bye
  5. String1
  6. String2

方法 3:手动方式

我们还可以手动将所有数组元素添加到ArrayList中。下面的示例显示了手动转换的逻辑。

  1. package beginnersbook.com;
  2. import java.util.*;
  3. public class Details {
  4. public static void main(String[] args) {
  5. /*ArrayList declaration*/
  6. ArrayList<String> arraylist= new ArrayList<String>();
  7. /*Initialized Array*/
  8. String array[] = {"Text1","Text2","Text3","Text4"};
  9. /*array.length returns the current number of
  10. * elements present in array*/
  11. for(int i =0;i<array.length;i++)
  12. {
  13. /* We are adding each array's element to the ArrayList*/
  14. arraylist.add(array[i]);
  15. }
  16. /*ArrayList content*/
  17. for(String str: arraylist)
  18. {
  19. System.out.println(str);
  20. }
  21. }
  22. }

输出:

  1. Text1
  2. Text2
  3. Text3
  4. Text4