ArrayListは、指定されたインデックスに存在する場合、要素を置き換えますか?


回答:


182
  arrayList.set(index i,String replaceElement);

3
「終了した場合の要素を置き換える」が、避けるのエラーには、nullチェックが必要-ここで問題自体はある
dev4u


パスインデックスなしの方法はありますか?
Arpit Patel 2016

@ArpitPatel arrayList.add()を使用して、新しい要素を追加できます。配列リストのどこにインデックスなしで何かを追加するかを指定することはできません。
アラン

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

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.