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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s