有 `new Class[]{}` 和 `new Class[0]` 之间有区别吗?

huangapple go评论86阅读模式
英文:

Is there a difference between new Class[]{} and new Class[0]?

问题

new Class[]{}new Class[0]之间有区别吗?如果有,有什么不同?

英文:

Is there a difference between new Class[]{} and new Class[0]? If yes, what is different?

答案1

得分: 6

没有区别。

反编译这段代码:

final class Foo {
  Class[] a = new Class[]{};
  Class[] b = new Class[0];
}

得到的结果是:

final class Foo {
  java.lang.Class[] a;

  java.lang.Class[] b;

  Foo();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: aload_0
       5: iconst_0
       6: anewarray     #2                  // class java/lang/Class
       9: putfield      #3                  // Field a:[Ljava/lang/Class;
      12: aload_0
      13: iconst_0
      14: anewarray     #2                  // class java/lang/Class
      17: putfield      #4                  // Field b:[Ljava/lang/Class;
      20: return
}

也就是说,这两种形式生成的字节码是完全相同的。

英文:

No difference.

Decompiling this:

final class Foo {
  Class[] a = new Class[]{};
  Class[] b = new Class[0];
}

yields

final class Foo {
  java.lang.Class[] a;

  java.lang.Class[] b;

  Foo();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object.&quot;&lt;init&gt;&quot;:()V
       4: aload_0
       5: iconst_0
       6: anewarray     #2                  // class java/lang/Class
       9: putfield      #3                  // Field a:[Ljava/lang/Class;
      12: aload_0
      13: iconst_0
      14: anewarray     #2                  // class java/lang/Class
      17: putfield      #4                  // Field b:[Ljava/lang/Class;
      20: return
}

That is, the two forms yield identical bytecode.

huangapple
  • 本文由 发表于 2020年9月21日 18:44:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63990703.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定