-2

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
    You shouldn't use "double brace initialization". It is considered an anti-pattern as it adds extra anonymous classes and can result in memory leaks because - if created in a non-static method - they will retain a reference to the enclosing object. See also [What is Double Brace initialization in Java?](https://stackoverflow.com/questions/1958636/what-is-double-brace-initialization-in-java) – Mark Rotteveel Feb 19 '23 at 13:21
  • Thanks @MarkRotteveel. I was not aware about this memory leak issue. – Gyanesh Sharma Feb 20 '23 at 10:46

1 Answers1

0

You can initialize a temporary variable to the current index value and use that.

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));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80