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でLongを比較するときの落とし穴

Posted at

1.背景

Java では Long や Integer は プリミティブ型(long, int) のラッパークラスです。
ラッパークラスをそのまま比較すると意図しない動作になることがあります。

2. よくある間違い

Long a = 127L;
Long b = 127L;

System.out.println(a == b);  //  ==> true
Long a = 128L;
Long b = 128L;

System.out.println(a == b);  //  ==> false

なぜ?
-128 ~ 127 の範囲は キャッシュされるため true になりますが、それ以外の値だと false。
つまり == で比較すると危険。

3. 正しい比較方法

1️⃣ equals を使う

Long a = 128L;
Long b = 128L;

if (a.equals(b)) {
    System.out.println("同じ値");
}

2️⃣ プリミティブに変換して比較

Long a = 128L;
Long b = 128L;

if (a.longValue() == b.longValue()) {
    System.out.println("同じ値");
}

3️⃣ null 安全に比較(おすすめ)

Long a = 128L;
Long b = 128L;

if (Objects.equals(a, b)) {
    System.out.println("同じ値");
}

4. Integer との比較

Long l = 128L;
Integer i = 128;

if (l.equals(Long.valueOf(i))) {
    System.out.println("同じ値");
}

注意⚠️ l.equals(i) は false になります(型が違うため)。

まとめ

  • == は使わない
  • a.equals(b) / Objects.equals(a, b) を使う
  • 型を揃えることが重要(データベースでは、一般的に ID は Long を使用し、状態や type などの値は Integer を使用します。)
0
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
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?