24

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

אורי orihpt
  • 2,358
  • 2
  • 16
  • 41
Steffan Harris
  • 9,106
  • 30
  • 75
  • 101

4 Answers4

42

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.

NullUserException
  • 83,810
  • 28
  • 209
  • 234
6

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

String[] words = ...;
List<String> wordList = Arrays.asList(words);
Richard Cook
  • 32,523
  • 5
  • 46
  • 71
  • 2
    This returns a fixed-size list of strings encapsulated by some private type that implements the List interface. @NullUserException's answer is the best if you need an instance of java.util.ArrayList that is mutable. – Richard Cook Sep 19 '10 at 17:15
  • Richard, just wanted to know that why is the above list becoming fixed-size? Can't I further add another element to the same list in the next line.. like wordList.add(anotherStringElement); – peakit Sep 19 '10 at 17:39
  • That's the defined behaviour of the asList method. As @NullUserException points out you should convert to an ArrayList [ArrayList aList = new ArrayList(Arrays.asList(words)] in order to obtain an ArrayList that you can add further items to. – Richard Cook Sep 19 '10 at 17:47
2

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);
slfan
  • 8,950
  • 115
  • 65
  • 78
Andy
  • 189
  • 1
  • 2
1

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]
MariusDL
  • 13
  • 4