24

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

4 Answers 4

43

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This answer is better than mine!
Collections.addAll(theList, anArray); did it for me. Thank you very much! :)
6

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

String[] words = ...;
List<String> wordList = Arrays.asList(words);

3 Comments

This returns a fixed-size list of strings encapsulated by some private type that implements the List<String> interface. @NullUserException's answer is the best if you need an instance of java.util.ArrayList that is mutable.
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);
That's the defined behaviour of the asList method. As @NullUserException points out you should convert to an ArrayList [ArrayList<Type> aList = new ArrayList<Type>(Arrays.asList(words)] in order to obtain an ArrayList that you can add further items to.
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);

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.