Java ArrayList replace at specific index
JavaArraylistJava 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
Use ArrayList.set
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 :