意識しておかないと間違いに気づかない可能性があるので、備忘録として保存する。
比較する場合の注意
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
を使って比較しよう。
参考