初始化ArrayList的简单方法总结

方法1

ArrayList places = new ArrayList(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

 方法2

ArrayList list = new ArrayList() {{
    add("A");
    add("B");
    add("C");
}} 

方法3

List places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata"); 

方法4

import com.google.common.collect.ImmutableList;

....

List places = ImmutableList.of("Buenos Aires", "Córdoba", "La Plata"); 

#方法5#

List strings = new ArrayList(asList("foo", "bar", "baz")) 

方法6

创建一个工厂方法:

public static ArrayList createArrayList(String ... elements) {
  ArrayList list = new ArrayList(); 
  for (String element : elements) {
    list.add(element);
  }
  return list;
}

....

ArrayList places = createArrayList(
  "São Paulo", "Rio de Janeiro", "Brasília"); 

更大的灵活性,它可以是一种通用:

public static  ArrayList createArrayList(T ... elements) { 
  ArrayList list = new ArrayList();  
  for (T element : elements) { 
    list.add(element); 
  } 
  return list; 
} 

你可能感兴趣的:(JAVA)