Wednesday, October 2, 2013

Converting between List and Array

Example to convert between List and Array:

Converting between List and Array
Converting between List and Array


package java_list;

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

/**
 * @web http://java-buddy.blogspot.com/
 */
public class Java_List {

    public static void main(String[] args) {

        String[] stringArrayOrg = {
            "One", "Two", "Three", "Four", "Five"
        };
        
        //Convert from Array of String to List of String
        List<String> stringList = Arrays.asList(stringArrayOrg);
        
        //Convert from List of String to Array of String
        String[] stringArray = (String[])stringList.toArray();
        
        System.out.println("stringList (List of String):");
        for(int i=0; i<stringList.size(); i++){
            System.out.println(stringList.get(i));
        }
        System.out.println();
        
        System.out.println("stringArray (Array of String):");
        for(int i=0; i<stringArray.length; i++){
            System.out.println(stringArray[i]);
        }
        System.out.println();
        
    }
}


No comments:

Post a Comment