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

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

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

这两者之间有什么实际差别吗?


希望这个链接能对你有所帮助:http://www.learn-java-tutorial.com/Arrays.cfm#.UpHnzdKBnto - Shamse Alam
重复的问题 http://stackoverflow.com/questions/19558078/declaring-arrays-in-java/19558227#19558227 - Ahmet Karakaya
3个回答

2
它们是等价的,两者之间没有区别。 new关键字创建一个对象...而你正在创建一个数组,它也是一个对象。
请参见第10章 数组

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


谢谢。我认为问题是:有没有什么难以理解的东西?例如 'new String("blabla")'。 - ferrerverck
不,Java中没有数组池。在Java中,字符串是特殊的,它们介于基本类型和对象之间。因此,String a = "hello";String a = new String("Hello"); 是不同的。 - Maroun
@ferrerverck 你可以看到这两个的字节码是完全相同的。 - Maroun

0

查看编译后的类文件的字节码,没有任何区别。

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

}

0

你的第二个表单只是第一个表单的语法简写。它们编译成完全相同的字节码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接