Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList replace element if exists at a given index?

Tags:

java

arraylist

How to replace element if exists in an ArrayList at a given index?

like image 946
Harinder Avatar asked Apr 11 '11 05:04

Harinder


People also ask

How do you replace an element in an ArrayList?

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.

Which method replaces an element at a specified position in an ArrayList?

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.

How do you update a value in an ArrayList in Java?

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.

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

  arrayList.set(index i,String replaceElement); 
like image 131
dev4u Avatar answered Sep 22 '22 22:09

dev4u


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  } 
like image 27
corsiKa Avatar answered Sep 19 '22 22:09

corsiKa