Assigning ArrayList Array in Java

I was wondering if it is possible to assign an ArrayList array in Java.

+20
java arraylist
Sep 19 '10 at 17:08
source share
4 answers

You can use Arrays.asList() :

 Type[] anArray = ... ArrayList<Type> aList = new ArrayList<Type>(Arrays.asList(anArray)); 

or alternatively Collections.addAll() :

 ArrayList<Type> aList = new ArrayList<Type>(); Collections.addAll(theList, anArray); 

Note that you are not randomly assigning an array to the list (well, you cannot do this), but I think this is the end result you are looking for.

+39
Sep 19 '10 at 17:11
source share
β€” -

The Arrays class contains the asList method, which you can use as follows:

 String[] words = ...; List<String> wordList = Arrays.asList(words); 
+6
Sep 19 '10 at 17:10
source share

If you import or you have an array (type strings) in your code, and you need to convert it to arraylist (offcourse string), then it is better to use collections. eg:

 String array1[] = getIntent().getExtras().getStringArray("key1"); or String array1[] = ... then List<String> allEds = new ArrayList<String>(); Collections.addAll(allEds, array1); 
+2
Dec 04 '14 at 12:14
source share

It works

  int[] ar = {10, 20, 20, 10, 10, 30, 50, 10, 20}; ArrayList<Integer> list = new ArrayList<>(); for(int i:ar){ list.add(new Integer(i)); } System.out.println(list.toString()); // prints : [10, 20, 20, 10, 10, 30, 50, 10, 20] 
0
May 18 '19 at 22:17
source share



All Articles