Friday, 29 January 2016

Convert Array to Arraylist in Java


Convert Array to java.util.Arraylist.
The JAVA collection API brings in more flexibility to the developer over what was offered by the JAVA Arrays. So time to time we might want to convert an array to a List or more commonly ArrayList.

The Syntax for the same goes like this:


  Object objectArray[] = {Object1, Object2, Object3};
  List<Object> objectList=Arrays.asList(objectArray);


Sample Program:

package net.codermag.example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArraylistTest {
 public static void main(String[] args) {

  String names[] = { "John", "Smith", "Doe" };

  List nameList = Arrays.asList(names);

  System.out.println(nameList.size());
  System.out.println(nameList);

  /*nameList.add("Lorem");
  nameList.add("Ipsum");
  System.out.println(nameList.size());
  System.out.println(nameList);*/

  List newNameList = new ArrayList(nameList);
  newNameList.add("Lorem");
  newNameList.add("Ipsum");

  System.out.println(newNameList.size());
  System.out.println(newNameList);
 }

}




Output:

3
[John, Smith, Doe]
5
[John, Smith, Doe, Lorem, Ipsum]


A pitfall you should know about:

The Arrays.asList() functions returns a List which is "immutable" with respect to the size.
This means we cannot add or remove an element from the List which is returned so in this case we cannot alter the list "nameList".

To demonstrate this you can try to run the code by uncommenting the commented out section.

/*nameList.add("Lorem");
nameList.add("Ipsum");
System.out.println(nameList.size());
System.out.println(nameList);*/

This gives the following Exception:

Exception in thread "main" java.lang.UnsupportedOperationException
 at java.util.AbstractList.add(AbstractList.java:148)
 at java.util.AbstractList.add(AbstractList.java:108)
 at net.codermag.example.ArraylistTest.main(ArraylistTest.java:17)

The Solution:
The solution to this problem is to assign the returned list "nameList" to a new list object "newNameList".
This will solve the issue and we can do all java.util.ArrayList based operations on this new list object.


No comments:

Post a Comment

Coder Magnet
CoderMagnet is full of resources from our daily development activities. It has solutions for common problematic scenarios in technologies like Java 8, AEM, JCR and also occasionally gives you tips on Blogger as well.