Initialize ArrayList in Java
package xiaoling; import ; import ; import ; public class ListTest{ public static void main(String[] args){ List<List<Integer>> list = new ArrayList<>(); for (int num=0; num<10; ++num){ (new ArrayList((num, num+1))); } (list); } }
The results of the run are: [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 10]]
Extended Learning:
Java Quickly create List collections
The code of a certain case in the program is as follows:
Map<String, List<CronTrigger>> tMap = new HashMap<String, List<CronTrigger>>(); (name, (new CronTrigger[] { trigger }));
The program run throws an exception:
Cause of error:
Methods are used to quickly create Lists, but the ArrayList returned by this method is not an object, but an inner class of Arrays.
We can check the source code
: @SafeVarargs public static <T> List<T> asList(T... a) { return new ArrayList<>(a); } --------------------------------------------------- private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, { private static final long serialVersionUID = -2764017481108945198L; private final E[] a; ArrayList(E[] array) { if (array==null) throw new NullPointerException(); a = array; } .....
In the above code, you can see that the inner class ArrayList inherits AbstractList
Thank you for your study and support.