如果给定索引处存在ArrayList替换元素?


82

如果在给定索引的ArrayList中存在元素,该如何替换?

Answers:



5

如果您需要不同的设置功能,建议您使用自己的类扩展ArrayList。这样,您就不必在多个地方定义行为。

// 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

}

2

如果元素已经存在于索引处,则该元素将被覆盖,这是默认行为:Javadoc

还是我完全想念你的意思?



0

只需在arraylist中使用此方法

list.set(/*index*/,/*value*/)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.