88

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

5 Answers 5

189
  arrayList.set(index i,String replaceElement);
Sign up to request clarification or add additional context in comments.

4 Comments

here the question itself is - "replace element if exits", but to avoid error, null check required
is there any way without pass index in it??
@ArpitPatel arrayList.add() can be used to append a new element. You cannot specify where in the array list you want to add something without an index.
5

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

}

Comments

2

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?

Comments

0

just use this method inside arraylist

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

Comments

-1

Just add a break after your remove() statement

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.