加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java Object.equals

发布时间:2020-12-15 05:01:08 所属栏目:Java 来源:网络整理
导读:有人能告诉我为什么这会返回真的吗? 我想如果我把东西投入到例如对象然后调用.equals, 将使用Object的默认实现.并且s1 == s2应该返回false: – / 请告诉我在哪个主题下我可以找到更多关于此行为的信息. SetString s1 = new HashSetString(as("a")); SetStr
有人能告诉我为什么这会返回真的吗?
我想如果我把东西投入到例如对象然后调用.equals,
将使用Object的默认实现.并且s1 == s2应该返回false: – /

请告诉我在哪个主题下我可以找到更多关于此行为的信息.

Set<String> s1 = new HashSet<String>(as("a"));
   Set<String> s2 = new HashSet<String>(as("a"));

   Object o1 = (Object)s1;
   Object o2 = (Object)s2;

   System.out.println(o1.equals(o2));

解决方法

Java中的方法默认是虚拟的.特别是,Object.equals是虚拟的(因为它没有被声明为 final).从 HashSet overrides Object.equals1开始,您将看到在对运行时类型为HashSet的对象上调用虚方法时使用的等于的HashSet实现(请记住 dynamic dispatch取决于接收对象的运行时类型,而不是编译时类型).

1:我们知道HashSet会覆盖Object.equals,因为documentation表示HashSet派生自AbstractSet,而AbstractSet.equals 的文档说:

Compares the specified object with this set for equality. Returns true if the specified object is also a set,the two sets have the same size,and every member of the specified set is contained in this set (or equivalently,every member of this set is contained in the specified set). This definition ensures that the equals method works properly across different implementations of the set interface.

它明确定义了值相等,而默认的Object.equals是身份相等.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读