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 5 years have passed since last update.

List<Integer>でremove(int),remove(Integer)するとどうなるか?

Posted at

Listでは以下のメソッドが定義されている.
・remove(int index)
・remove(Object o)

前者はインデックス指定で削除するもので、後者はオブジェクト指定で削除するもの.

さて「Integerの場合にどのような動作になるのだろうか?」というのが問題.

結果を見てもらえば瞭然だが、引数がintの場合はインデックス削除になっており、Integerの場合はオブジェクト削除になっている.

一応常識的な結果ではあるが「Listの削除では、AutoBoxingを当てにしてはいけない」ということになる.

これでバグったら、ちょっと分かりにくいような気がする....

Tips0004.java
package jp.avaj.lib.algo;
import java.util.List;
import jp.avaj.lib.test.L;

public class Tips0004 {
  public static void main(String[] args) {
    Integer[] integerArray = new Integer[] {
      9,8,7,6,5,4,3,2,1,0
    };
    List<Integer> integerList;

    // インデックスで削除(しているつもり).
    integerList = ArArray.toList(integerArray);
    integerList.remove(8);
    L.p(ArObj.toString(integerList));

    // オブジェクトで削除(しているつもり).
    integerList = ArArray.toList(integerArray);
    integerList.remove(new Integer(8));
    L.p(ArObj.toString(integerList));
  }
}

結果は以下の通り。

[9, 8, 7, 6, 5, 4, 3, 2, 0]
[9, 7, 6, 5, 4, 3, 2, 1, 0]
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?