首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java ArrayList 雙大括號初始化報錯:正確的集合初始化方式

     編輯:程式設計疑難解答

代碼 new ArrayList<DeviceSettingEntry>() { { ""; 1; }; } 使用雙大括號初始化(匿名內部類 + 實例初始化塊),但塊內語法錯誤:`""; 1;` 不是合法語句,且泛型類型 `DeviceSettingEntry` 不匹配字符串/整數字面量。

錯誤原因

  • 實例初始化塊 `{ ... }` 內必須是合法 Java 語句,`""; 1;` 是兩個無意義的表達式語句,編譯器報錯。
  • 泛型為 `DeviceSettingEntry`,添加元素需 `add(new DeviceSettingEntry(...))`,而非基本類型字面量。
  • 雙大括號初始化會創建匿名內部類,持有外部類引用,可能導致內存洩漏,不推薦生產使用。

正確初始化方式

1. Java 9+ List.of(不可變)

List<DeviceSettingEntry> list = List.of(
  new DeviceSettingEntry("param1", 1),
  new DeviceSettingEntry("param2", 2)
);
// 如需可變列表
List<DeviceSettingEntry> mutable = new ArrayList<>(list);

2. 傳統 add 方式(通用)

List<DeviceSettingEntry> list = new ArrayList<>();
list.add(new DeviceSettingEntry("param1", 1));
list.add(new DeviceSettingEntry("param2", 2));

3. 工具類輔助(Guava/Apache Commons)

// Guava
List<DeviceSettingEntry> list = Lists.newArrayList(
  new DeviceSettingEntry("param1", 1),
  new DeviceSettingEntry("param2", 2)
);

4. 雙大括號正確語法(僅演示,不推薦)

List<DeviceSettingEntry> list = new ArrayList<DeviceSettingEntry>() {{
  add(new DeviceSettingEntry("param1", 1));
  add(new DeviceSettingEntry("param2", 2));
}};

如何將 null 轉為目標對象?

問題截圖顯示想在初始化時放入 `null` 後再替換。正確做法:

List<DeviceSettingEntry> list = new ArrayList<>(Collections.nCopies(10, null));
// 後續按索引替換
list.set(0, new DeviceSettingEntry("a", 1));

或直接 `add` 真實對象,無需佔位 `null`。

總結

  • 雙大括號初始化語法錯誤且有副作用,棄用。
  • 優先用 `List.of`(不可變)或 `new ArrayList<>()` + `add`。
  • 泛型類型必須匹配添加的元素類型。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved