写入构造函数中成员变量的数据类型会引发什么问题?

huangapple go评论60阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年9月16日 10:57:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63912463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定