英文:
Local variables referenced from an inner class must be final or effectively final - Java
问题
当尝试使用索引作为值初始化ArrayList时,我遇到了错误消息 "局部变量在内部类中必须是final或有效final的,位置在<add(index);>"
int index=0;
for (int i:nums){
if (!map.containsKey(i)){
ArrayList<Integer> al1=new ArrayList<Integer>(){{
add(index);
}};
map.put(i,al1);
}
index+=1;
}
我知道有可能的解决方法,只需声明ArrayList,然后分别添加值,这完全有效。
ArrayList<Integer> al1=new ArrayList<Integer>();
al1.add(index);
map.put(i,al1);
但我想了解是否有办法在初始化时实现它。
请帮我解决这个问题。先谢谢!
英文:
When attempting to initialize an ArrayList with an index as a value, I encounter the error message "local variables referenced from an inner class must be final or effectively final at <add(index);>"
int index=0;
for (int i:nums){
if (!map.containsKey(i)){
ArrayList<Integer> al1=new ArrayList<Integer>(){{
add(index);
}};
map.put(i,al1);
}
index+=1;
}
I know there are possible walkarounds where I can just simply declare arraylist then add value to it separately, this works totally fine.
ArrayList<Integer> al1=new ArrayList<Integer>();
al1.add(index);
map.put(i,al1);
But I want to understand whether there's any way to achieve it during initialization itself.
Please help me with this. Thanks in advance!
答案1
得分: 0
你可以将一个临时变量初始化为当前的 `index` 值并使用它。
```java
final int temp = index; // 这实际上是不可变的
ArrayList<Integer> al1 = new ArrayList<Integer>(){{
add(temp);
}};
然而,在这种情况下,更好的做法可能是使用 List.of
、Arrays.asList
或 Collections.singletonList
。
List<Integer> al1 = List.of(index);
// 或者,如果特别需要 ArrayList:
ArrayList<Integer> al1 = new ArrayList<>(List.of(index));
<details>
<summary>英文:</summary>
You can initialize a temporary variable to the current `index` value and use that.
```java
final int temp = index; // this is effectively final
ArrayList<Integer> al1=new ArrayList<Integer>(){{
add(temp);
}};
However, in this case, it is probably better to use List.of
, Arrays.asList
, or Collections.singletonList
.
List<Integer> al1 = List.of(index);
// or, if an ArrayList is specifically required:
ArrayList<Integer> al1 = new ArrayList<>(List.of(index));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论