Java List初始化的例子

1. 使用双括号初始化(Double Brace Initialization)

复制代码
public static final List<Integer> FIELD_KILL_CHAIN_LIST = new ArrayList<Integer>() {{
    add(1);
    add(6);
}};

注意: 这种方式会创建匿名子类,在某些情况下可能不是最佳选择。

2. 使用 Arrays.asList()(推荐)

复制代码
public static final List<Integer> FIELD_KILL_CHAIN_LIST = Arrays.asList(1, 6);

3. 使用 List.of()(Java 9+ 推荐)

复制代码
public static final List<Integer> FIELD_KILL_CHAIN_LIST = List.of(1, 6);

4. 使用 Collections.unmodifiableList()

复制代码
public static final List<Integer> FIELD_KILL_CHAIN_LIST = 
    Collections.unmodifiableList(Arrays.asList(1, 6));

5. 分步初始化

复制代码
public static final List<Integer> FIELD_KILL_CHAIN_LIST;

static {
    List<Integer> tempList = new ArrayList<>();
    tempList.add(1);
    tempList.add(6);
    FIELD_KILL_CHAIN_LIST = Collections.unmodifiableList(tempList);
}
相关推荐
4***17271 小时前
【MySQL篇】使用Java操作MySQL实现数据交互
java·mysql·交互
人工智能训练1 小时前
Windows系统Docker中Xinference 集群无法启动的解决方法
linux·运维·服务器·windows·docker·容器·xinference
sheji34161 小时前
【开题答辩全过程】以 基于Spring Boot的流浪动物救助系统设计为例,包含答辩的问题和答案
java·spring boot·后端
程序员霸哥哥1 小时前
XYplorer(多标签文件管理器) v27.20.0700 / 28.00.1200 多语便携版
windows·macos·软件工程·mac·应用软件·xyplorer
W***r261 小时前
VScode 开发 Springboot 程序
java·spring boot·后端
公子小六1 小时前
推荐一种手动设置异步线程等待机制的解决方案
windows·microsoft·c#·.net
MacroZheng1 小时前
取代Navicat!全新一代数据库管理工具来了,超级智能!
java·后端·mysql
w***i2942 小时前
Spring Boot实现定时任务
java·spring boot·后端