英文:
What is the problem of writing data type of member variable in constructor?
问题
以下是翻译好的内容:
public class Set {
int[] elements;
public Set() {
elements = new int[0];
}
}
上述代码会引发空指针异常。
相比之下,以下代码不会引发空指针异常,并且正常工作。
public class Set {
int[] elements;
public Set() {
elements = new int[0];
}
}
这两段代码唯一的区别是是否为成员变量 int[] elements
赋值。
为什么类型会引发异常?
我猜想构造函数不会执行任何操作。但我发现构造函数实际上通过构造函数执行了某些神秘的操作。那么在第一个代码中构造函数实际上执行了什么操作,为什么会引发异常?
英文:
public class Set {
int[] elements;
public Set() {
int[] elements= new int[0];
}
}
The code above cause NullPointerException.
In contrast the code bellow don't cause NullpointerExceoption and works well.
public class Set {
int[] elements;
public Set() {
elements= new int[0];
}
}
The only difference between two codes are whether giving int[] which is type of member variable or not.
Why type cause exception?
My guess was that constructor would not do anything. But I found that it do something mysterious by constructor. Then what does the constructor actually do in first code and why it cause the exception?
答案1
得分: 0
在第一个示例中,int[] elements = new int[0];
你定义了一个名为 elements 的局部变量,它是一个大小为 0 的数组。
在第二个示例中,你将大小为 0 的数组赋值给了实例变量 elements。
英文:
In the first example, int[] elements = new int[0];
you define a local variable, elements, as an array of size 0.
In the second example, you assign an array of size 0 to the instance variable elements.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论