我正在编写代码以存储数组元素的索引
TreeMap<Integer, ArrayList<Integer>> map = new TreeMap<>();
for (int i = 1; i <= n; i++) {
int num = Integer.parseInt(stt.nextToken());
if (map.containsKey(num)) {
map.get(num).add(i);
} else {
map.put(num, new ArrayList<Integer>() {
{
add(i); // here
}
});
}
}
但在//此处注释的行,它给了我
编译错误Local variable i defined in an enclosing scope must be final or effectively final
为什么?
知道当我将i的值保存在另一个变量中时
TreeMap<Integer, ArrayList<Integer>> map = new TreeMap<>();
for (int i = 1; i <= n; i++) {
int num = Integer.parseInt(stt.nextToken());
if (map.containsKey(num)) {
map.get(num).add(i);
} else {
int ind = i; // it worked fine
map.put(num, new ArrayList<Integer>() {
{
add(ind);
}
});
}
}