测试环境
$ java -version
java version "1.8.0_251"
Java(TM) SE Runtime Environment (build 1.8.0_251-b08)
Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)
方式一:
常规方式
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(5);
System.out.println(list);
// [1, 5]
方式二:
addAll方法
List<Integer> obj = new ArrayList<>();
List<Integer> list = Arrays.asList(1, 2, 3);
obj.addAll(list);
System.out.println(obj);
// [1, 2, 3]
方式三:
Arrays.asList()方法
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));
System.out.println(list);
// [1, 2, 3]
方式四:
匿名内部类
List<String> list = new ArrayList<String>() {
{
add("1");
add("2");
}
};
System.out.println(list);
// [1, 2]
完整代码
package com.example;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArrayTest {
@Test
public void testInit1() {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(5);
System.out.println(list);
// [1, 5]
}
@Test
public void testInit2() {
List<Integer> obj = new ArrayList<>();
List<Integer> list = Arrays.asList(1, 2, 3);
obj.addAll(list);
System.out.println(obj);
// [1, 2, 3]
}
@Test
public void testInit3() {
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));
System.out.println(list);
// [1, 2, 3]
}
@Test
public void testInit4() {
List<String> list = new ArrayList<String>() {
{
add("1");
add("2");
}
};
System.out.println(list);
// [1, 2]
}
}
标签:初始化,Java,list,ArrayList,List,System,add,new From: https://blog.51cto.com/mouday/6203276