为什么我不应该在Java8中对Optional使用基于身份的操作? [英] Why should I not use identity based operations on Optional in Java8?

查看:117
本文介绍了为什么我不应该在Java8中对Optional使用基于身份的操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.util.Optional 的javadoc声明:

The javadoc for java.util.Optional states that:


这是一个基于价值的阶级;在Optional的实例上使用身份敏感操作(包括引用相等(==),标识哈希代码或同步)可能会产生不可预测的结果,应该避免使用。

This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of Optional may have unpredictable results and should be avoided.

但是,这个junit片段是绿色的。为什么?它似乎与javadoc相矛盾。

However, this junit snippet is green. Why? It seems to contradict the javadoc.

    Optional<String> holder = Optional.ofNullable(null);
    assertEquals("==", true, holder == Optional.<String>empty());
    assertEquals("equals", true, holder.equals(Optional.<String>empty()));


推荐答案

你不应该从观察到的行为中得出任何结论在一个特定的实现下运行一个简单的测试。规范说你不能依赖这种行为,因为API设计者保留自己随时更改行为的选项,恕不另行通知。

You shouldn’t draw any conclusions from the observed behavior of one simple test ran under a particular implementation. The specification says that you can’t rely on this behavior, because the API designers reserve themselves the option to change the behavior at any time without notice.

术语基于价值的班级已经提供了暗示预期的选择。当进行具有相同值的重复调用时,未来版本或替代实现可能返回相同的实例,或者JVM可能实现基于身份的操作没有意义的真值类型。

The term Value-based Class already provides a hint about the intended options. Future versions or alternative implementations may return the same instance when repeated calls with the same value are made, or the JVM might implement true value types for which identity based operations have no meaning.

这类似于包装类型的装箱 valueOf 方法返回的实例。除了为某些(小)值所做的保证之外,未指定是创建新实例还是为相同值返回相同的实例。

This is similar to instances returned by the boxing valueOf methods of the wrapper types. Besides the guaranty made for certain (small) values, it is unspecified whether new instances are created or the same instance is returned for the same value.

程序可能产生如果它试图将两个引用区分为基于值的类的相等值,则不可预测的结果......也可能意味着参考比较的结果可能在两个基于值的类实例的生命周期内更改。考虑重复数据删除功能。由于JVM已经为 String 的内部 char [] 数组提供了这样的功能,因此扩展此功能的想法对基于价值的类的所有实例的功能并不是那么牵强。

"A program may produce unpredictable results if it attempts to distinguish two references to equal values of a value-based class…" could also imply that the result of a reference comparison may change during the lifetime of two value-based class instances. Think of a de-duplication feature. Since the JVM already has such a feature for the internal char[] array of Strings, the idea of expanding this feature to all instances of "value-based classes" isn’t so far-fetched.

这篇关于为什么我不应该在Java8中对Optional使用基于身份的操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆