Tuesday, May 31, 2011

How to Convert an Array to a List

This piece of Java code shows how to convert an array to one of the Collection types, namely a List.
There is a class called Arrays (not to be confused with an array) that has a method called as List() which takes an array as argument and converts it to a List object. Generics can be used to specify the List elements type.

package org.best.example;

public class Main {
  
    public void arrayToList() {
      
        String[] cars = {"Dodge", "Chevrolet", "BMW", "Toyota"};
        List<String> carList = Arrays.asList(cars);

        for (String car : carList) {
            System.out.println(car);
        }
    }
    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().arrayToList();
    }
}

No comments: