2011-04-11 78 views

回答

135
arrayList.set(index i,String replaceElement); 
+9

仅供参考,如果没有一个元素在我那么这个位置将引发错误 – 2012-04-17 11:23:30

+2

这个问题本身是 - “如果退出替换元素”,但为了避免错误,空检查需要 – dev4u 2012-06-12 05:35:13

+0

HTTP:// WWW。 java2s.com/Code/Java/Collections-Data-Structure/ReplaceanelementatspecifiedindexofJavaArrayList.htm – ktaria 2014-12-16 08:08:25

4

如果你打算要求不同的功能集,我建议用你自己的类来扩展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

或者我完全错过了你的观点?