gpt4 book ai didi

Java 对象.等于

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:34:08 29 4
gpt4 key购买 nike

有人能告诉我为什么这会返回 true 吗?我想如果我投一些东西给例如Object 然后调用.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));

最佳答案

因为这正是 Javadocs 的内容说它会做:

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

仅仅因为您将它转换为 Object 并不会改变它的实际情况。使用了 HashSet 中覆盖的 equals() 方法。

关于Java 对象.等于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17383190/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com