本地变量在内部类中被引用时必须是 final 或 effectively final – Java

huangapple go评论64阅读模式
英文:

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&lt;Integer&gt; al1=new ArrayList&lt;Integer&gt;(){{
                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&lt;Integer&gt; al1=new ArrayList&lt;Integer&gt;();
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.ofArrays.asListCollections.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&lt;Integer&gt; al1=new ArrayList&lt;Integer&gt;(){{
	add(temp);
}};

However, in this case, it is probably better to use List.of, Arrays.asList, or Collections.singletonList.

List&lt;Integer&gt; al1 = List.of(index);
// or, if an ArrayList is specifically required:
ArrayList&lt;Integer&gt; al1 = new ArrayList&lt;&gt;(List.of(index));

huangapple
  • 本文由 发表于 2023年2月19日 11:34:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497813.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定