Skip to content

Instantly share code, notes, and snippets.

@ezura
Created July 6, 2017 02:33
Show Gist options
  • Select an option

  • Save ezura/37db38fc66c2bd24681c9b11a03338b1 to your computer and use it in GitHub Desktop.

Select an option

Save ezura/37db38fc66c2bd24681c9b11a03338b1 to your computer and use it in GitHub Desktop.
む…。畳み込み?だとしても、300 === 300 だし参照は等価じゃないような… 127 まではプールされてるの使いまわされるのはわかるんだけど… #CodePiece #kotlin
val v: Int? = 300
val v2: Int? = 300
v === v2
// false
val v: Int = 300
val v2: Int = 300
v === v2
// true
@ezura

ezura commented Jul 7, 2017

Copy link
Copy Markdown
Author

これだ!
https://gist.github.com/ezura/ba9279b9e2b5cafa26d725c415d7ca5d

   public static final void f() {
      Integer v = Integer.valueOf(300);
      Integer v2 = Integer.valueOf(300);
      boolean var10000;
      if(v == v2) {
         var10000 = true;
      } else {
         var10000 = false;
      }

   }

   public static final void _f() {
      int v = 300;
      int v2 = 300;
      boolean var10000;
      if(v == v2) {
         var10000 = true;
      } else {
         var10000 = false;
      }

   }

@ezura

ezura commented Jul 7, 2017

Copy link
Copy Markdown
Author

@hshiozawa

Copy link
Copy Markdown

ちょっと気をつけないといけないのは、

Integer a = Integer.valueOf(1);
Integer b = Integer.valueOf(1);

や、

Integer a = 1;
Integer b = 1;

だと、 a == btrue になることです。

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