[英]How to add an item after another item in List?
我想在特定项目后面的列表中添加一个项目。
例:
"Item 1"
"Item 2"
"Item 3"
"Item 4"
添加新项目:
String newItem = "Item 5"
list.add(newItem);
现在我希望我添加的项目低于某个项目,让我们假设后者:
"Item 1"
"Item 2"
"Item 5"
"Item 3"
"Item 4"
List
接口有方法void add(int index,E element)方法
将指定元素插入此列表中的指定位置(可选操作)。
在你的情况下
list.add(2,newItem);
注意:索引从零开始。
在使用该方法之前。 请查看下面的例外情况
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())
String = "Item 5"
list.add(3,newItem);
会为你做的伎俩......
它的
list.add(index,itemtobeadded )
使用List接口的LinkedList
类
List<String> list = new LinkedList<String>();
public void addItem(String item, String afterItem, List<String> list){
int location = list.indexOf(afterItem);
list.add(location+1, item);
}
public static void main(String args[]){
TestClass obj = new TestClass();
obj.list.add("1");
obj.list.add("2");
obj.list.add("3");
obj.list.add("4");
obj.list.add("5");
for (String s: obj.list)
System.out.println(s);
obj.addItem("6", "3", obj.list);
for (String s: obj.list)
System.out.println(s);
}
如果你使用对象数组,它总是一个好习惯
Object[] array= new Object[7];
array[0]="Item 1";
array[1]="Item 3";
array[2]="Item 2";
array[3]= array[2]
最后,你可以使用这个,如果你想用作列表使用这个转换,
List<Object> list= Arrays.asList(array);
谢谢和问候,哈里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.