Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 什么';这两种声明的优点是什么?_Java_Arrays - Fatal编程技术网

Java 什么';这两种声明的优点是什么?

Java 什么';这两种声明的优点是什么?,java,arrays,Java,Arrays,我有一个关于数组声明样式的问题 //I get that you may just want to initliaze array with 0s for some reason int[] myIntArray = new int[3]; //I get that you already know what values you want in this array int[] myIntArray = {1, 2, 3}; 在这两种符号中声明的优点是什么: //Woulnd't I ju

我有一个关于数组声明样式的问题

//I get that you may just want to initliaze array with 0s for some reason
int[] myIntArray = new int[3];

//I get that you already know what values you want in this array
int[] myIntArray = {1, 2, 3};
在这两种符号中声明的优点是什么:

//Woulnd't I just use the 1st notation for this
int[] myIntArray;
myIntArray=new int[3];


第四种表示法几乎与第二种表示法相同,只是有两个引用,
myIntArray
和一个
anonymous
数组,指向对象
{1,2,3}
,其中第二种引用,
anonymous
立即丢失

int[/myIntArray={1,2,3}
int[]myIntArray=newint[]{1,2,3}是指第一种语法仅在初始化变量时起作用

因此,如果您有这样的代码:

int[] myIntArray = {1, 2, 3};
// some code
if (someCondition) {
  myIntArray= new int[] {4, 5, 6};
}
您可以用
{4,5,6}
替换第二个,因为该语法仅用于初始化

但是
newint[]{4,5,6}
是一个基本上在任何地方都能工作的通用表达式

它主要用于构造数组而不是将其分配给变量的情况,例如直接将其传递给方法调用:

someFunctionTakingAnIntArray(new int[] {3, 4, 5});

事实上,存在一种处理事物的方法并不意味着它是有用的。3)如果(出于任何原因)您希望将数组“初始化”为
null
,并在以后给它一个适当的(空)数组,那么它可能是有用的;4) AFAIK是(2)之前的旧语法,但仍然有效。@tobias_k编号3未将
myIntArray
设置为null(至少如果它是局部变量),而是使其未初始化。只有字段在未显式初始化时才获得默认值。@JoachimSauer我了解到未初始化的引用变量默认为
NULL
。@HelloWorld:这只适用于字段。未初始化的局部变量只是未初始化的:在编译器确信它们确实已被赋值之前,不允许读取它们。这是否意味着第四种符号仅在非常人为的情况下有用(数组必须很小,我才能手动初始化)?因为我可能可以使用一些方法来修改数组?@HelloWorld:在任何情况下,如果您想构造一个值,但不将其分配给变量,例如直接调用函数时,它都很有用:
somefunctiontakingtarray(new int[]{3,4,5})
。在这里,你不能使用快捷方式。
someFunctionTakingAnIntArray(new int[] {3, 4, 5});