ArrayList replace element if exists at a given index?

前端 未结 5 1564
鱼传尺愫
鱼传尺愫 2021-02-02 04:48

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

5条回答
  •  抹茶落季
    2021-02-02 05:37

    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 extends java.util.ArrayList {
    
        @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
    
    }
    

提交回复
热议问题