1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Apex】【エラー】System.ListException: List index out of bounds

Posted at

やろうとしたこと

とあるクラスのインスタンスを作ると、itemsにデフォルトで4要素追加される。
removeItemsメソッドはデフォルト4アイテムのうち2~4番目を削除する。

↓例えばこんなかんじ

public class piepie001 {
    // なんかリスト
    List<string> items = new List<string>();
    
    // コンストラクタ
    public piepie001(){
        // デフォルトでアイテム4つを追加
        items.add('a');
        items.add('b');
        items.add('c');
        items.add('d');
    }
    
    // アイテム削除
    public void removeItems(){
        // 2~4番目のアイテムを削除
        items.remove(1);
        items.remove(2);
        items.remove(3);
    }
}

エラー

上記のコードでremoveItems()を実行すると、、

System.ListException: List index out of bounds: 3

が発生する

前の要素から削除すると要素数減るので
items.remove(3);でそんな要素ねえ!と怒られるわけです。

修正

しょうもないミスでした、気を付けます。

    // アイテム削除
    public void removeItems(){
        // 2~4番目のアイテムを削除
        items.remove(3);
        items.remove(2);
        items.remove(1);
    }
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?