繁体   English   中英

我们声明数组的方式之间有什么区别吗?

[英]Is there any difference between ways we are declaring arrays?

  • int[] a = new int[] {1, 2, 3};

  • int[] a = {1, 2, 3};

这些之间是否存在实际差异?

它们是等价的,两者没有区别。

new关键字创建一个对象 ..你正在创建一个数组 ,它是一个对象。

第10章。数组

在Java编程语言中, 数组是对象 (§4.3.1) ......

你的第二种形式只是第一种形式的句法简写。 它们编译成完全相同的字节码。

从编译的类文件中查看字节码,没有区别。

public class XFace  {

    public void test1(){
        int[] a = new int[] {1, 2, 3};
    }


    public void test2(){
        int[] a = {1, 2, 3};

    }

}

Compiled from "XFace.java"
public class XFace extends java.lang.Objec
public XFace();
  Code:
   0:   aload_0
   1:   invokespecial   #8; //Method java/
   4:   return

public void test1();
  Code:
   0:   iconst_3
   1:   newarray int
   3:   dup
   4:   iconst_0
   5:   iconst_1
   6:   iastore
   7:   dup
   8:   iconst_1
   9:   iconst_2
   10:  iastore
   11:  dup
   12:  iconst_2
   13:  iconst_3
   14:  iastore
   15:  astore_1
   16:  return

public void test2();
  Code:
   0:   iconst_3
   1:   newarray int
   3:   dup
   4:   iconst_0
   5:   iconst_1
   6:   iastore
   7:   dup
   8:   iconst_1
   9:   iconst_2
   10:  iastore
   11:  dup
   12:  iconst_2
   13:  iconst_3
   14:  iastore
   15:  astore_1
   16:  return

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM