Monday, September 23, 2013

How to convert an Array to a List object?

converting an Array to List: 

The below code shows you how to convert an Array to List object

code snippet:
 
        String[] str=new String[2];
        str[0]="nagarjuna";
        str[1]="kalyan";
       
        List<String> lstr=Arrays.asList(str);
       
        for(String s:lstr){
            System.out.println(s);
        }//end


The resultant is the List<String> type object, And the object 'lstr' is an implementation is of ArrayList type.
But this ArrayList is not expected ArrayList that availables in java.util.ArrayList.

This ArrayList is a private inner class in Arrays class.

If we observe the below code snippet, we can understand what is going in the back ground.

code snippet:
        System.out.println(lstr instanceof java.util.ArrayList);
        System.out.println(lstr.getClass().getName());//end

If we run the above code, we get the output like

o/p:
false
java.util.Arrays$ArrayList


So the implementation of the List is of type ArrayList which is available in the package java.util.Arrays$ArrayList



Please give your feedback at nagarjuna.lingala@gmail.com



No comments:

Post a Comment