ArrayList replace element if exists at a given index?

JavaArraylist

Java Problem Overview


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

Java Solutions


Solution 1 - Java

  arrayList.set(index i,String replaceElement);

Solution 2 - Java

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

}

Solution 3 - Java

An element is over-written if it already exists at an index, that is the default behaviour: Javadoc.

Or am I missing your point completely?

Solution 4 - Java

just use this method inside arraylist

list.set(/*index*/,/*value*/)

Solution 5 - Java

Just add a break after your remove() statement

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
QuestionHarinderView Question on Stackoverflow
Solution 1 - Javadev4uView Answer on Stackoverflow
Solution 2 - JavacorsiKaView Answer on Stackoverflow
Solution 3 - Javauser183037View Answer on Stackoverflow
Solution 4 - JavayousefView Answer on Stackoverflow
Solution 5 - JavaSebastian AltamiranoView Answer on Stackoverflow