[英]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.