神刀安全网

Convert Array to ArrayList in Java

In this tutorial you will learn how to convert array to arraylist in Java.

There are mainly two ways to convert a Java array to arraylist.

  • Using Arrays.asList() method
  • Using Collections.addAll() method

Below I have shared an example of each of these methods. In these examples we are converting string array to arraylist.

Also Read:  Convert ArrayList to Array in Java

Convert Array to ArrayList in Java

Convert Array to ArrayList in Java

1. Using Arrays.asList() method

The asList() method of Arrays class directly converts an array to arraylist. It has following syntax.

ArrayList<T> arrayList=new ArrayList<T>(Arrays.asList(array));
ArrayList<T> arrayList=new ArrayList<T>(Arrays.asList(array)); 

Example

package com;  import java.util.ArrayList; import java.util.Arrays;  public class ArrayToArrayList {  public static void main(String...s){   String str[]={"C","C++","Java","Android","JavaScript"};    //converting Array to ArrayList   ArrayList<String> al=new ArrayList<String>(Arrays.asList(str));      for(int i=0;i<al.size();++i){    System.out.println(al.get(i));   }  } }
package com;   import java.util.ArrayList; import java.util.Arrays;   public class ArrayToArrayList {     public static void main(String...s){         String str[]={"C","C++","Java","Android","JavaScript"};           //converting Array to ArrayList         ArrayList<String> al=new ArrayList<String>(Arrays.asList(str));                  for(int i=0;i<al.size();++i){             System.out.println(al.get(i));         }     } } 

Output

C

C++

Java

Android

JavaScript

2. Using Collections.addAll() method

The addAll() method of Collections class can also be used for converting array to arraylist. It is faster than Arrays.asList() method. It has following syntax.

Collections.addAll(arrayList,array);
Collections.addAll(arrayList,array); 

Example

package com;  import java.util.ArrayList; import java.util.Collections;  public class ArrayToArrayList {  public static void main(String...s){   String str[]={"C","C++","Java","Android","JavaScript"};   ArrayList<String> al=new ArrayList<String>();    //converting Array to ArrayList   Collections.addAll(al,str);      for(int i=0;i<al.size();++i){    System.out.println(al.get(i));   }  } }
package com;   importjava.util.ArrayList; importjava.util.Collections;   public class ArrayToArrayList {     public static void main(String...s){         String str[]={"C","C++","Java","Android","JavaScript"};         ArrayList<String> al=new ArrayList<String>();           //converting Array to ArrayList         Collections.addAll(al,str);                  for(int i=0;i<al.size();++i){             System.out.println(al.get(i));         }     } } 

Output

C

C++

Java

Android

JavaScript

Comment below if you have doubts related to above array to arraylist examples.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Convert Array to ArrayList in Java

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮