Java: Converting a List to an Array

For some reason, I always keep forgetting how to do this, without using a for-loop.


import java.util.ArrayList; 
import java.util.List; 

public class ConvertListToArray { 
 public static void main(String[] args) {
  ArrayList list = new ArrayList(); 
  list.add("test1"); list.add("test2"); 
  list.add("test3"); 
  String[] arrayOfStrings = convertListToArray(list); 
  for (String string : arrayOfStrings) { 
   System.out.println(string); 
  } 
 } 
 private static String[] convertListToArray(List list) { 
  return (String[]) list.toArray(new String[0]); 
 } 
} 
Advertisements
This entry was posted in code example, java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s