初始化ArrayList的簡單方法總結

FeelTouch發表於2018-06-18

方法1

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

 方法2

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

方法3

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

方法4

import com.google.common.collect.ImmutableList;

....

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

#方法5#

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

方法6

建立一個工廠方法:

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

....

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

更大的靈活性,它可以是一種通用:

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

相關文章