我想在列表中的特定项目之后添加一个项目。
例子:
"Item 1"
"Item 2"
"Item 3"
"Item 4"
Run Code Online (Sandbox Code Playgroud)
添加新项目:
String newItem = "Item 5"
list.add(newItem);
Run Code Online (Sandbox Code Playgroud)
现在我希望我添加的项目低于某个项目,让我们假设后者:
"Item 1"
"Item 2"
"Item 5"
"Item 3"
"Item 4"
Run Code Online (Sandbox Code Playgroud)
List接口有方法void add(int index, E element)方法
在此列表中的指定位置插入指定元素(可选操作)。
在你的情况下
list.add(2,newItem);
Run Code Online (Sandbox Code Playgroud)
注意:索引从零开始。
在使用该方法之前。只需检查以下异常
UnsupportedOperationException - if the add operation is not supported by this list
ClassCastException - if the class of the specified element prevents it from being added to this list
NullPointerException - if the specified element is null and this list does not permit null elements
IllegalArgumentException - if some property of the specified element prevents it from being added to this list
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())
Run Code Online (Sandbox Code Playgroud)