0
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?

javaのリスト要素をfor文内で操作した際に生んだ不具合

Posted at

あらまし

javaでListを使用している際に特定条件の要素を削除したい.
for文で要素を比較し,該当レコードを削除するコード(該当のコード抜粋)を作成したが,一部要素が削除されていなかった.

該当のコード抜粋.java
List<String> list = new ArrayList<>(List.of("A", "B", "B", "C"));
for (int i = 0; i < list.size(); i++) {
    if ("B".equals(list.get(i))) {
        list.remove(i);
    }
}

for文で比較している要素を出力してみる

ソースコードに比較要素を出力する文を追加し,実行してみる.

.java
List<String> list = new ArrayList<>(List.of("A", "B", "B", "C"));
for (int i = 0; i < list.size(); i++) {
    System.out.println(i + ":" + list.get(i));
    if ("B".equals(list.get(i))) {
        System.out.println("remove B");
        list.remove(i);
    }
}
System.out.println(list);
実行結果.txt
0:A
1:B
remove B
2:C
[A, B, C]

結論

  • forの条件式は参照ごとに更新される
  • listのインデックスはremove直後に更新される
    上記2つのことより,1つ目の"B"をremoveした直後に2つ目の"B"がインデックス[1]に格納され,if文で比較されなかったことがわかった.
0
0
1

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
0
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?