java - 比较对象及其成员变量

标签 java jakarta-ee compare

假设我有两个相同类的对象,例如:

public class Example {
    String name;
    String rollNo;
    String address;
    String phoneNo;
    String city;
}

Example obj1 = new Example();
    obj1.name = "Name";
    obj1.rollNo = "10";
    obj1.address = "Address";
    obj1.phoneNo = "Phone Number";
    obj1.city = "City";

Example obj2 = new Example();
    obj2.name = "Name";
    obj2.rollNo = "10";
    obj2.address = "Address";
    obj2.phoneNo = "Phone Number";
    obj2.city = "City";

这里我想比较 obj1obj2 问题是我不想用 if 条件来做这个,即获取 obj1< 的每个成员变量 然后将其与 obj2 变量进行比较。

java.lang.Object 类的

equals 方法在这里不起作用,因为它比较对象引用。

我的问题是,是否有任何 Java API 可以比较两个对象及其成员变量。

最佳答案

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Example other = (Example) obj;
        if (address == null) {
            if (other.address != null)
                return false;
        } else if (!address.equals(other.address))
            return false;
        if (city == null) {
            if (other.city != null)
                return false;
        } else if (!city.equals(other.city))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (phoneNo == null) {
            if (other.phoneNo != null)
                return false;
        } else if (!phoneNo.equals(other.phoneNo))
            return false;
        if (rollNo == null) {
            if (other.rollNo != null)
                return false;
        } else if (!rollNo.equals(other.rollNo))
            return false;
        return true;
    }

将这个 equals 函数粘贴到您的 exmaple 类中,然后像这样比较对象:

 if(obj1.equals(obj2)) {  //will return true now

 }

关于java - 比较对象及其成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21280582/

相关文章:

c - 关于浮子特性的问题

laravel - 如何比较 Laravel 中的碳日期?

javascript - 将数组元素与 javascript 中的特定字符串进行比较

java - @Asynchronous 在抽象类中工作吗?

java - 无法将 JMenuBar 添加到 Applet

java - 在没有注释或 xml 配置的情况下创建主要 bean

java - 如何解决recyclerview中的重复数据

java - 是否有任何基于 Java 的开源框架可以根据带有分隔符的键字符串从文本字段中查找值?

java - 不明白这个异常是从哪里来的?

JavaMelody 在启动 Tomcat 时抛出 NullPointerException