Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList replace at specific index

Tags:

java

arraylist

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) {  } 
like image 808
user949902 Avatar asked Sep 17 '11 05:09

user949902


People also ask

How do I change the value of a particular index in an ArrayList?

Use the ArrayList. add(int index, Object value) method to add any object or element at the specific index of ArrayList and use ArrayList. set(int index, E value) to replace the value at the specific index of ArrayList in java.

How do you modify an element in an ArrayList in Java?

To replace an existing element, we must find the exact position (index) of the element in arraylist. Once we have the index, we can use set() method to update the replace the old element with new element. Find index of existing element using indexOf() method. Use set(index, object) to update new element.

Can I modify ArrayList while iterating?

ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration.


2 Answers

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

like image 86
TotoroTotoro Avatar answered Sep 28 '22 20:09

TotoroTotoro


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

like image 42
Android Killer Avatar answered Sep 28 '22 18:09

Android Killer