Created
July 6, 2017 02:33
-
-
Save ezura/37db38fc66c2bd24681c9b11a03338b1 to your computer and use it in GitHub Desktop.
む…。畳み込み?だとしても、300 === 300 だし参照は等価じゃないような…
127 まではプールされてるの使いまわされるのはわかるんだけど… #CodePiece #kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| val v: Int? = 300 | |
| val v2: Int? = 300 | |
| v === v2 | |
| // false | |
| val v: Int = 300 | |
| val v2: Int = 300 | |
| v === v2 | |
| // true |
Author
Author
ちょっと気をつけないといけないのは、
Integer a = Integer.valueOf(1);
Integer b = Integer.valueOf(1);や、
Integer a = 1;
Integer b = 1;だと、 a == b が true になることです。
Integer は 128 ~ 127 の値を持つ Integer オブジェクトをキャッシュして使い回しているからです。
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/lang/Integer.java?av=f#780
これは実装上の最適化ではなく Java 言語の仕様なのでちょっと注意が必要です。
https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.7
If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between '\u0000' and '\u007f' inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.
もちろん、次のように明示的にオブジェクトを生成すれば a != b になりますね。
Integer a = new Integer(1);
Integer b = new Integer(1);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
これだ!
https://gist.github.com/ezura/ba9279b9e2b5cafa26d725c415d7ca5d