Java - Convert a list into an array of a specific class

By xngo on February 27, 2019

Show how to convert a list into an array of specific class using toArray().

import java.util.ArrayList;
 
public class ToArrayInSpecificClassType
{
    public static void main(String[] args){
        // Create sample data.
        ArrayList<String> lStrings = new ArrayList<String>();
        lStrings.add("ab"); lStrings.add("cd"); lStrings.add("ef");
 
        // This will return an array of object. It isn't what we want.
        Object[] oStrings = lStrings.toArray();
 
        // This will return an array of specific class type(i.e String).
        String[] aStrings = lStrings.toArray(new String[0]);
    }
}

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.