这是初始化java.util.ArrayList
的几种方法,请参见以下完整示例:
InitArrayList.java
package com.mkyong.examples;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class InitArrayList {
public static void main(String[] args) {
//1. Normal way
List<String> list = new ArrayList<String>();
list.add("String A");
list.add("String B");
list.add("String C");
System.out.println("List 1......");
for (String temp : list) {
System.out.println(temp);
}
//2. Anonymous inner class
List<String> list2 = new ArrayList<String>() {
{
add("String A");
add("String B");
add("String C");
}
};
System.out.println("List 2......");
for (String temp : list2) {
System.out.println(temp);
}
//3. One line
List<String> list3 = Arrays.asList("String A", "String B", "String C");
System.out.println("List 3......");
for (String temp : list3) {
System.out.println(temp);
}
}
}
输出量
List 1......
String A
String B
String C
List 2......
String A
String B
String C
List 3......
String A
String B
String C
翻译自: https://mkyong.com/java/how-to-initialize-an-arraylist-in-one-line/