开发者

Java ArrayList replace at specific index

开发者 https://www.devze.com 2023-04-05 17:27 出处:网络
I need help with this java please. I created an ArrayList of bulbs, and I\'m trying to replace a bulb at specific index with another bulb. So开发者_开发问答 with the following heading, how do I procee

I need help with this java please. I created an ArrayList of bulbs, and I'm trying to replace a bulb at specific index with another bulb. So开发者_开发问答 with the following heading, how do I proceed?

public void replaceBulb(int index, Bulbs theBulb) {

}


Check out the set(int index, E element) method in the List interface


You can replace the items at specific position using set method of ArrayList as below:

list.set( your_index, your_item );

But the element should be present at the index you are passing inside set() method else it will throw exception.

Also you can check oracle doc here


Use the set() method: see doc

arraylist.set(index,newvalue);


Use ArrayList.set


public void setItem(List<Item> dataEntity, Item item) {
    int itemIndex = dataEntity.indexOf(item);
    if (itemIndex != -1) {
        dataEntity.set(itemIndex, item);
    }
}


Lets get array list as ArrayList and new value as value all you need to do is pass the parameters to .set method. ArrayList.set(index,value)

Ex -

ArrayList.set(10,"new value or object")
0

精彩评论

暂无评论...
验证码 换一张
取 消