[英]What is the difference between creating an array object and assigning arrays with curly braces?
[英]What is the difference between just declaring array of object and actually creating instance of it?
为什么第一个语句输出“nothing1”而第二个语句不输出? 如果我没有错,那么在语句second中新创建的对象数组具有默认引用null。
class Solution
{
public static void main (String[] args) throws java.lang.Exception
{
Animal temp1[]=null;//statement first;
if(temp1==null)
System.out.println("nothing1");
Animal temp2[]=new Animal[5];//statement second;
if(temp2==null)
System.out.println("nothing2");
}
}
class Animal
{
int name;
int action;
public Animal(int name, int action) {
this.name = name;
this.action = action;
}
}
第一个声明
Animal temp1[]=null;
声明一个数组变量并将其初始化为null。 因此打印“nothing1”。
第二个声明
Animal temp2[]=new Animal[5];
声明一个数组变量并将其初始化为长度为5的数组。此数组的元素(例如temp2[0]
)最初都为null
,但数组引用本身( temp2
)不为null。 因此不打印“nothing2”。
在第一种情况下,数组尚未分配任何内存,但在以后的情况下,您已初始化了数组,因此需要一些内存块进行初始化,因此它的引用现在将指向一个内存位置,并且不会为null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.