2017-12-18 205 views
0

这两行代码之间是否存在显着差异?新int [] {}之间的区别或者只是{}

int[] array = new int[]{1,2,3} 
int[] array = {1,2,3} 

如果我不得不猜测,相同的构造函数在第二个版本中隐式调用,使它们相同。

编辑: This question was explored previously here but with default values.我的问题考虑了非默认值的数组的初始化。

+0

你有没有试过反汇编字节码,看看有没有什么明显的区别? – Veera

回答

2

只是出于好奇,我也去编译类以下方法

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

public void arrayTest2(){ 
    int[] array = {1,2,3}; 
} 

下面是与之相关的结果。

public void arrayTest1(); 
    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 arrayTest2(); 
    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

谢谢!这是很好的知道。这是我原来的帖子中的一条评论:“你试过拆开字节码,看看有没有什么明显的区别?” - 维拉“。这是你做的吗?这是如何完成的? – Andrew

+0

[javap](https://docs.oracle.com/javase/7/docs/technotes/tools/windows/javap.html)由Java发行版提供,允许您反汇编字节码。在这种情况下,我运行了-c选项 – Veera

+0

感谢[Pshemo](https://stackoverflow.com/users/1393766/pshemo)添加更多细分代码。 – Veera

相关问题