Java ArrayList replace at specific index

JavaArraylist

Java Problem Overview


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

}

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

Use the set() method: see doc

arraylist.set(index,newvalue);

Solution 4 - Java

Solution 5 - Java

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

Solution 6 - Java

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

Solution 7 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser949902View Question on Stackoverflow
Solution 1 - JavaTotoroTotoroView Answer on Stackoverflow
Solution 2 - JavaAndroid KillerView Answer on Stackoverflow
Solution 3 - JavaBurt BeckwithView Answer on Stackoverflow
Solution 4 - JavaOceanicView Answer on Stackoverflow
Solution 5 - JavaKhaled LelaView Answer on Stackoverflow
Solution 6 - JavaDinithView Answer on Stackoverflow
Solution 7 - JavaAnuj DhimanView Answer on Stackoverflow