How to replace element if exists in an ArrayList at a given index?
You can replace an element of an ArrayList using the set() method of the Collections class. This method accepts two parameters an integer parameter indicating the index of the element to be replaced and an element to replace with.
void add(int index, E element) //inserts element at the given position in the array list. This method Replaces the element at the specified position in this list with the specified element.
To update or set an element or object at a given index of Java ArrayList, use ArrayList. set() method. ArrayList. set(index, element) method updates the element of ArrayList at specified index with given element.
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.
arrayList.set(index i,String replaceElement);
If you're going to be requiring different set functionaltiy, I'd advise extending ArrayList with your own class. This way, you won't have to define your behavior in more than one place.
// You can come up with a more appropriate name public class SizeGenerousArrayList<E> extends java.util.ArrayList<E> { @Override public E set(int index, E element) { this.ensureCapacity(index+1); // make sure we have room to set at index return super.set(index,element); // now go as normal } // all other methods aren't defined, so they use ArrayList's version by default }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With