Java数组声明 [英] Java arrays declarations

查看:91
本文介绍了Java数组声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好!



Java中的两个数组声明有什么区别吗?





Hello!

Is there any difference between the two array declaration in Java?


int[] myIntArray = {1,2,3};

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







我知道第一个数组存储在dinamycally中记忆,但第一个怎么样?

我应该使用其中一个吗?




I know that the first array is stored dinamycally in memory, but what about the first one?
Should I use one or the other?

推荐答案

最上面一个是 array-literal (或常量数组),第二个是数组声明。当你立即分配没有区别时,它们都以完全相同的方式动态分配。



唯一的区别是数组文字只能在数组变量的初始化期间使用,这意味着你不能使用文字语法来重新赋值数组。

The top one is an array-literal (or constant array), the second one is an array declaration. When you assign immediately there's no difference, they're both allocated dynamically in exactly the same way.

The only difference is that a array-literal can only be used during initialization of an array variable, meaning you can't use the literal syntax to re-assign the value of an array.
// Here, these are equivalent
int[] a = new int[] { 1, 2, 3};
int[] b = {1, 2, 3};

// They differ during re-assignment
a = new int[] { 4, 5, 6}; // This is fine, a now "points" to a new array.
b = {4, 5, 6}; // Will not compile!



希望这有帮助,

Fredrik


Hope this helps,
Fredrik


没有区别。

-SA


这篇关于Java数组声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆