0
0

More than 1 year has passed since last update.

参照型とプリミティブ型の比較は注意しよう

Last updated at Posted at 2022-10-30

意識しておかないと間違いに気づかない可能性があるので、備忘録として保存する。

比較する場合の注意

int num = 100;
int anotherNum = 100;

Integer refNum = 100;
Integer refAnotherNum = 100;

//数値自体を比較するため、TRUE
System.out.println(num == anotherNum);
//プリミティブ型のラッパークラスはある範囲でインスタンスをキャッシュする。
//その範囲は-128~127なので、100の場合は上手くいってしまう。
System.out.println(refNum == refAnotherNum);

実は参照型は、インスタンス同士を比較するので==, <=などで比較しても正しい結果になるとは限らない。
それは知っている人が多いと思うが、逆にうまくいってしまうパターンもある。

特に「参照型」と意識しないと忘れやすいIngtegerは注意しておきたい。
「数値」という意識が主になってしまって、不等号で比較しないように気を付けよう。

Integerを比較する場合

値の大小比較は、compareToを使用
同値の比較はequalsを使って比較しよう。

参考

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