且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么原始数据类型不能为“null”。在Java?

更新时间:2023-01-01 09:57:09

原始类型只是数据。另一方面,我们称之为对象的只是指向数据存储位置的指针。例如:

A primitive type is just data. What we call objects, on the other hand, are just pointers to where the data is stored. For example:

Integer object = new Integer(3);
int number = 3;

在这种情况下, object 只是一个指向其值为3的Integer对象的指针。也就是说,在存储变量对象的内存位置,您所拥有的只是对数据实际位置的引用。另一方面,存储 number 的内存位置直接包含值3.

In this case, object is just a pointer to an Integer object whose value happens to be 3. That is, at the memory position where the variable object is stored, all you have is a reference to where the data really is. The memory position where number is stored, on the other hand, contains the value 3 directly.

所以,你可以将对象设置为null,但这只是意味着该对象的数据为空(即未分配)。你不能将int设置为null,因为语言会将其解释为值0。

So, you could set the object to null, but that would just mean that the data of that object is in null (that is, not assigned). You cannot set an int to null, because the language would interpret that as being the value 0.

希望有帮助!