import java.util.ArrayList;
public class ArrayTest {
private static ArrayList<String> list = new ArrayList<String>();
public static void printList () {
System.out.println("Printing the list");
for (int i = 0; i < list.size(); i++)
{
if (list.get(i) != null)
System.out.println(i + " => " + list.get(i));
}
}
public static void add(Integer index, String val) {
while(list.size() <= index)
list.add(null);
list.add(index, val);
}
public static void main(String[] args) {
ArrayTest.add(8, "cover");
ArrayTest.printList();
ArrayTest.add(6, "and");
ArrayTest.printList();
}
}
产生以下输出
Printing the list
8 => cover
Printing the list
6 => and
9 => cover
该add(Integer index, String val)
函数将适当数量的空值添加到列表中作为检查以避免任何IndexOutOfBoundsException
异常。有人可以解释为什么在列表中添加“和”会推动“覆盖”列表中的位置吗?