Thursday, January 6, 2011

Conversion between Array and java.util.List

While dealing with Autogenerated Classes Like JAXB or any other framework we need to convert from Array to List or vice versa..

Object[] --> java.util.List
java.util.List --> Object[].

Array to List
    public static void main(String[] args) {
           String[] names= {"Name 1","Name 3","Name 4"};
           List nameList=Arrays.asList(names);
           System.out.println("List Size is :"+nameList.size());
           System.out.println("Names are :"+nameList);
It will give the Output as
   List Size is :3
   Names are :[Name 1, Name 3, Name 4]

We know how to insert the data in some position in List, But the insertion will not be allowed in the List provided by Arrays.asList,

It throws the following Exception when we do
   nameList.add(2,"Name 2");
   nameList.add("Name 2");

   Exception in thread "main" java.lang.UnsupportedOperationException
           at java.util.AbstractList.add(
           at java.util.AbstractList.add(
Reason: Reference
Arrays.asList Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray.

But as the array supported
    names[1] ="Name 2";
    The same functionality will be supported by List also , as follows.
    nameList.set(1,"Name 2");
List to Array

List to Array can be done using the following Code.
String[] namesArray = nameList.toArray(new String[0]);
      in JDK 1.4 we need to do teh following type casting.
      String[] namesArray = (String[])nameList.toArray(new String[0]);

No comments: