java - Java 中什么是 null?

标签 java null terminology

什么是null

null 是任何事物的实例吗?

null 属于什么集合?

它在内存中是如何表示的?

最佳答案

Is null an instance of anything?

不,没有 null 的类型是 instanceof .

15.20.2 Type Comparison Operator instanceof

RelationalExpression:
    RelationalExpression instanceof ReferenceType

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

这意味着对于任何类型 ER ,对于任何 E o ,其中o == null , o instanceof R总是false .

<小时/>

What set does 'null' belong to?

JLS 4.1 The Kinds of Types and Values

There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.

<小时/>

What is null?

正如上面引用的 JLS 所说,实际上,您可以简单地假装它“只是一个可以是任何引用类型的特殊文字”。

在 Java 中,null == null (在其他语言中情况并非总是如此)。另请注意,根据契约(Contract),它还具有此特殊属性(来自 java.lang.Object ):

public boolean equals(Object obj)

For any non-null reference value x, x.equals(null) should return false.

它也是所有引用类型的默认值(对于具有它们的变量):

JLS 4.12.5 Initial Values of Variables

  • Each class variable, instance variable, or array component is initialized with a default value when it is created:
    • For all reference types, the default value is null.

其使用方式各不相同。您可以使用它来启用字段的延迟初始化,其中字段的初始值为 null直到它被实际使用,它被“真实”值替换(计算起来可能很昂贵)。

还有其他用途。让我们以 java.lang.System 为例。 :

public static Console console()

Returns: The system console, if any, otherwise null.

这是一种非常常见的使用模式:null用于表示对象不存在。

这是另一个用法示例,这次来自 java.io.BufferedReader :

public String readLine() throws IOException

Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached.

所以在这里,readLine()将返回instanceof String对于每一行,直到它最终返回 null来表示结束。这允许您按如下方式处理每一行:

String line;
while ((line = reader.readLine()) != null) {
   process(line);
}

可以设计 API,使终止条件不依赖于 readLine()返回null ,但是可以看出,这样的设计有一个好处,就是让事情变得简洁。注意空行没有问题,因为空行"" != null .

让我们再举一个例子,这次是 java.util.Map<K,V> :

V get(Object key)

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

If this map permits null values, then a return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.

这里我们开始看看如何使用null会使事情变得复杂。第一条语句表示如果 key 未映射,null被返回。第二个语句表示即使键被映射,null也可以返回。

相比之下, java.util.Hashtable 通过不允许 null 让事情变得更简单键和值;它的V get(Object key) ,如果返回 null ,明确表示该键未映射。

您可以通读其余 API 并找到位置和方式 null用来。请记住,它们并不总是最佳实践示例。

一般来说,null用作特殊值来表示:

  • 未初始化状态
  • 终止条件
  • 不存在的对象
  • 未知值
<小时/>

How is it represented in the memory?

在 Java 中?与你无关。最好保持这种方式。

<小时/>

null是件好事吗?

现在这已经是主观的了。有人说null导致许多本来可以避免的程序员错误。有人说,用一种捕捉 NullPointerException 的语言与 Java 一样,使用它是很好的,因为你会因为程序员的错误而快速失败。有些人回避null通过使用 Null object pattern

这本身就是一个很大的主题,因此最好将其作为另一个问题的答案进行讨论。

我将引用 null 的发明者的话来结束本文。他自己,C.A.R Hoare (因快速排序而闻名):

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

video of this presentation更深入;这是一款值得推荐的 watch 。

关于java - Java 中什么是 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29480182/

相关文章:

coldfusion - 如何检查 ColdFusion 查询循环中的返回值是否为空值

language-agnostic - 当 write 或 read 返回的请求少于请求时如何调用它?

algorithm - 这个算法流程符号的名称是什么?

php - 01/01/1970 当 symfony 中的日期为空时

c - 当接收到 null-but-not-0 和 0-but-not-null 指针时,如何测试代码的行为?

url - URL sans 查询参数的正确术语是什么?

java - 字谜检查的最佳解决方案?

java - Apache commons 文件上传替代方案

java - 检测 JFileChooser 何时关闭

java - 在java中搜索重复的组合键