ArrayList 替换元素(如果存在于给定索引处)?
如果存在于给定索引的ArrayList中,如何替换元素?
arrayList.set(index i,String replaceElement);
如果你需要不同的集合函数,我建议你用你自己的类扩展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
}