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

2022-08-31 11:59:08

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


答案 1
  arrayList.set(index i,String replaceElement);

答案 2

如果你需要不同的集合函数,我建议你用你自己的类扩展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

}

推荐