JMemo040

BACK

Integerのリストに目的の数字が含まれているか判定

数値群の中から目的の数値が含まれているか探すのに、Listのcontainsを使えばいいと思いました。

しかしここで疑問なのが、

  • Listにはプリミティブ型の値は入れられないので、IntegerのListということになる。
  • Integerはオブジェクトである。
  • オブジェクト同士の比較だと、正しく値を探すことができないのでは? ということです。

そこで検証用に、次のようなコードを書いてみました。

List<Integer> list = new ArrayList<Integer>();

list.add(3);
list.add(7);
list.add(202);
list.add(45);

System.out.println(list.contains(3));
System.out.println(list.contains(2));
System.out.println(list.contains(45));
System.out.println(list.contains(707));

見事、true, false, true, false と狙い通りの値が表示されました!

ということは、IntegerのListのcontainsメソッドを使って目的を達成することは可能ということです。

でもどうしてそれが可能なの?

というわけで、今度はこんなコードを書いてみました。

Integer i1 = new Integer(1);
Integer i2 = new Integer(1);
System.out.println(i1.equals(i2));

String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1.equals(s2));

Exception e1 = new Exception();
Exception e2 = new Exception();
System.out.println(e1.equals(e2));

e1 = new Exception(new ArithmeticException());
e2 = new Exception(new ArithmeticException());
System.out.println(e1.equals(e2));

e1 = new Exception("abc");
e2 = new Exception("abc");
System.out.println(e1.equals(e2));

true, true, false, false, false と表示されます。 Stringがこうなるのは良く知られていると思いますが、Integerもそうなんですね。 オブジェクト同士の比較ではなくて値同士の比較になるんですね。

ではということで、Integerクラスのequalsメソッドを確認してみました。

public boolean equals(Object obj) {
if (obj instanceof Integer) {
    return value == ((Integer)obj).intValue();
}
return false;

ちゃんと値同士の比較になってました。(JDK6.0で確認)

最終更新:2013年08月30日 10:47