[英]Java ArrayList replace at specific index
我需要這個java的幫助。 我創建了一個燈泡 ArrayList,我試圖用另一個燈泡替換特定索引處的燈泡。 那么對於以下標題,我該如何進行?
public void replaceBulb(int index, Bulbs theBulb) {
}
查看List接口中的set(int index, E element)
方法
您可以使用 ArrayList 的 set 方法替換特定位置的項目,如下所示:
list.set( your_index, your_item );
但是元素應該出現在你在 set() 方法中傳遞的索引處,否則它會拋出異常。
您也可以在此處查看 oracle 文檔
使用set()
方法: 參見文檔
arraylist.set(index,newvalue);
public void setItem(List<Item> dataEntity, Item item) {
int itemIndex = dataEntity.indexOf(item);
if (itemIndex != -1) {
dataEntity.set(itemIndex, item);
}
}
我們可以使用 ArrayList Set() 方法替換 arraylist 中的元素。我們是一個例子,如下所示。
創建數組列表
ArrayList<String> arr = new ArrayList<String>();
arr.add("c");
arr.add("php");
arr.add("html");
arr.add("java");
現在替換索引 2 上的元素
arr.set(2,"Mysql");
System.out.println("after replace arrayList is = " + arr);
輸出 :
after replace arrayList is = [c, php, Mysql, java]
參考 :
讓我們將數組列表作為ArrayList
並將新值作為value
您需要做的就是將參數傳遞給.set
方法。 ArrayList.set(index,value)
前任 -
ArrayList.set(10,"new value or object")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.