Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning an array to an ArrayList in Java

Is it possible to assign an array to an ArrayList in Java?

like image 838
Steffan Harris Avatar asked Sep 19 '10 17:09

Steffan Harris


People also ask

Can you put arrays in ArrayList?

ArrayList of arrays can be created just like any other objects using ArrayList constructor. In 2D arrays, it might happen that most of the part in the array is empty. For optimizing the space complexity, Arraylist of arrays can be used.

Can you assign an ArrayList to another in Java?

The clone() method of the ArrayList class is used to clone an ArrayList to another ArrayList in Java as it returns a shallow copy of its caller ArrayList.


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 aren't technically assigning an array to a List (well, you can't do that), but I think this is the end result you are looking for.

like image 72
NullUserException Avatar answered Sep 28 '22 05:09

NullUserException


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

String[] words = ...;
List<String> wordList = Arrays.asList(words);
like image 34
Richard Cook Avatar answered Sep 28 '22 05:09

Richard Cook


If you are importing or you have an array (of type string) in your code and you have to convert it into arraylist (offcourse string) then use of collections is better. like this:

String array1[] = getIntent().getExtras().getStringArray("key1"); or
String array1[] = ...
then

List<String> allEds = new ArrayList<String>();
Collections.addAll(allEds, array1);
like image 42
Andy Avatar answered Sep 28 '22 06:09

Andy


This is working

    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]
like image 33
JamesBong Avatar answered Sep 28 '22 06:09

JamesBong