代碼 new ArrayList<DeviceSettingEntry>() { { ""; 1; }; } 使用雙大括號初始化(匿名內部類 + 實例初始化塊),但塊內語法錯誤:`""; 1;` 不是合法語句,且泛型類型 `DeviceSettingEntry` 不匹配字符串/整數字面量。
List<DeviceSettingEntry> list = List.of(
new DeviceSettingEntry("param1", 1),
new DeviceSettingEntry("param2", 2)
);
// 如需可變列表
List<DeviceSettingEntry> mutable = new ArrayList<>(list);
List<DeviceSettingEntry> list = new ArrayList<>();
list.add(new DeviceSettingEntry("param1", 1));
list.add(new DeviceSettingEntry("param2", 2));
// Guava
List<DeviceSettingEntry> list = Lists.newArrayList(
new DeviceSettingEntry("param1", 1),
new DeviceSettingEntry("param2", 2)
);
List<DeviceSettingEntry> list = new ArrayList<DeviceSettingEntry>() {{
add(new DeviceSettingEntry("param1", 1));
add(new DeviceSettingEntry("param2", 2));
}};
問題截圖顯示想在初始化時放入 `null` 後再替換。正確做法:
List<DeviceSettingEntry> list = new ArrayList<>(Collections.nCopies(10, null));
// 後續按索引替換
list.set(0, new DeviceSettingEntry("a", 1));
或直接 `add` 真實對象,無需佔位 `null`。