Java: convert between List and Array








I. List to Array

List<String> list = new ArrayList<String>(Arrays.asList(new String[]{"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus"})); 
// NOTE: the following line can be 
// String[] array = list.toArray(new String[0]);
String[] array = list.toArray(new String[list.size()]);

II.Array to List

String[] array = new String[]{"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus"};
List<String> list = Arrays.asList(array);

III. A complete example

package arc;

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

public class Test {

 public static void main(String[] args) {
  String[] array = new String[] { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus" };
  for (String a : array) {
   System.out.println(a);
  }
  
  List<String> list = toList(array);
  System.out.println(list);
  
  array = toArray(list);
  for (String a : array) {
   System.out.println(a);
  }
 }

 public static String[] toArray(List<String> list) {
  return list.toArray(new String[0]);
 }

 public static List<String> toList(String[] array) {
  return Arrays.asList(array);
 }

}

NOTE

list.toArray(new String[0]) is ok because the method will create a new array with the actual size of the list and returns it.


No comments:

Post a Comment