Arrays.fill

the two code blocks would return different results

List<Integer>[] rg = new List[n]; Arrays.fill(rg, new ArrayList<>()); ...List<List<Integer>> rg = new ArrayList<>(); for (int i = 0; i < n; ++i) { rg.add(new ArrayList<>()); } ...

turns out, with Arrays.fill, it first calculate the second parameter, then using that parameter to assign every array element

public static void fill(Object[] a, Object val) { for (int i = 0, len = a.length; i < len; i++) a[i] = val; }

while the `rg.add(new ArrayList<>());` would always get a different object for each element.

Originally published at https://lwpro2.dev on August 5, 2021.