Sec*_*ret 3 java data-structures
为什么以下返回IndexOutOfBoundsException?(索引5,大小0)
gridList = new ArrayList<Integer>(9);
gridList.add(5, 2);
Run Code Online (Sandbox Code Playgroud)
我的印象是构造函数调用将我的arraylist初始化为大小.
我对java很新,所以道歉.
调用该构造函数只是指定初始容量,但对ArrayList的大小没有影响(在添加任何内容之前,大小始终为零).这在文档中有解释,也可以通过打印出ArrayList来证明:
ArrayList<Integer> gridList = new ArrayList<Integer>(9);
System.out.println(gridList);
Output: []
Run Code Online (Sandbox Code Playgroud)
如果要初始化一个包含9个整数的ArrayList(例如,9个零),请尝试以下" 方便实现 ":
ArrayList<Integer> gridList = new ArrayList<Integer>(Collections.nCopies(9, 0));
System.out.println(gridList);
Output: [0, 0, 0, 0, 0, 0, 0, 0, 0]
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这会在初始化期间使用值填充ArrayList,因此您现在可以在gridList.add(5, 2);没有的情况下调用IndexOutOfBoundsException.