ArrayList replace element if exists at a given index?

扶醉桌前 提交于 2020-04-07 13:55:34

问题


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


回答1:


  arrayList.set(index i,String replaceElement);



回答2:


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

}



回答3:


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?




回答4:


Just add a break after your remove() statement



来源:https://stackoverflow.com/questions/5617175/arraylist-replace-element-if-exists-at-a-given-index

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!