gpt4 book ai didi

java - equals 方法在字符串和列表中的使用

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:19:52 25 4
gpt4 key购买 nike

在 oracle java 文档中,list 中的 equals() 表示如果两个列表包含相同的元素,则它们被定义为相等。但是只有当它们的哈希码相等时,对象类 equals() 才返回 true。这意味着列表中的 equals() 覆盖了对象类中的 equals 方法。字符串中的 equals() 也是一样的。只要它们具有相同的字符,它们就会返回 true。

所以每当我将类型声明为 String,或使用像 arraylist 这样的列表类时equals() 会被自动覆盖吗?

最佳答案

equals() are overridden automatically righT?

回答: 是的,绝对正确,如果你问重写 .equals()方法在运行时自动调用

**对象类是java中每个类的父类,它由.equals()组成。比较对象引用的方法

但是String类,包装类 (Integer,Long etc..)和 Collection 类 (ArrayList, hashSet etc..)被覆盖 .equals()比较对象中的内容而不是对象引用的方法

为了避免混淆这里是一个明显的例子

public class Main2 {
public static void main(String[] args) {
List<String> l1 = new ArrayList<>();
l1.add(new String("hello"));
List<String> l2 = new ArrayList<>();
l2.add(new String("hello"));

System.out.println(l1.equals(l2)); //true

List<Test> t1 = new ArrayList<>();
t1.add(new Test());
List<Test> t2 = new ArrayList<>();
t2.add(new Test());

System.out.println(t1.equals(t2)); //false
}
}

class Test{
}

在上面的例子中比较List<String>将返回 true 因为 .euqals() String 中的方法被覆盖以比较内容

但是比较Lits<Test>即使两个对象都是空的,也会返回 false,因为 .equals() Test 中的方法默认情况下不会覆盖类,它将调用 Object.equals()比较对象引用的方法 ==

Google Question 对象类 equals 方法比较哈希码?

回答

The java.lang.Object class requires that any two objects that compare equal using the equals() method must produce the same integer result when the hashCode() method is invoked on the objects [API 2014]. The equals() method is used to determine logical equivalence between object instances.Feb 12, 2018

关于java - equals 方法在字符串和列表中的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53661319/

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