[java] Java ArrayList replace at specific index

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) {

}

This question is related to java arraylist

The answer is


Use the set() method: see doc

arraylist.set(index,newvalue);

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.



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

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


We can replace element in arraylist using ArrayList Set() method.We are a example for this as below.

Create Arraylist

 ArrayList<String> arr = new ArrayList<String>();
 arr.add("c");
 arr.add("php");
 arr.add("html");
 arr.add("java");

Now replcae Element on index 2

 arr.set(2,"Mysql");
 System.out.println("after replace arrayList is = " + arr);

OutPut :

 after replace arrayList is = [c, php, Mysql, java]

Reference :

Replace element in ArrayList


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")