使用匿名代表时出现编译错误。的arrayList

时间:2019-07-12 22:08:34

标签: java arraylist

我正在编写代码以存储数组元素的索引

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);
                        }
                    });
                }
            }

0 个答案:

没有答案