检查对象字段是否已存在于另一个实例中

huangapple go评论65阅读模式
英文:

Check if Object fields already exists in another instance

问题

我正在创建多个相同对象的实例,并且我想检查两个字段以了解是否有重复。

public class Professor {
    String name;
    String surName;
    String department;

    // 构造方法,设置器和获取器
}

public class DProf {
    String depName;
    private static List<Professor> professors = new ArrayList<>();

    // 构造方法,设置器和获取器

    public void addProfessor(Professor professor) {
        if (containsName(professor.name) && containsSurName(professor.surName)) {
            return;
        } else {
            professors.add(professor);
            new Professor(professor);
        }
    }

    public boolean containsName(final String name) {
        return professors.stream().anyMatch(o -> o.getName().equals(name));
    }

    public boolean containsSurName(final String surName) {
        return professors.stream().anyMatch(o -> o.getSurName().equals(surName));
    }
}

编辑:目前的方法是将教授存储在List<Professors>中,并使用两个方法检查名字和姓氏是否存在。

英文:

I'm creating multiple instances of the same object and I want to check two fields to know if it has duplicates.

public class Professor {
    String name;
    String surName;
    String department;

    // Contructors, Setter and Getters
}

public class DProf {
    String depName;
    private static List&lt;Professor&gt; professors = new ArrayList&lt;&gt;();

    // Contructors, Setter and Getters

    public void addProfessor(Professor professor) {
        if (containsName(professor.name) &amp;&amp; containsSurName(professor.surName)) {
            return;
        } else {
            professors.add(professor);
            new Professor(professor);
        }
    }

    public boolean containsName(final String name) {
        return professors.stream().anyMatch(o -&gt; o.getName().equals(name));
    }

    public boolean containsSurName(final String surName) {
        return professors.stream().anyMatch(o -&gt; o.getSurName().equals(surName));
    }
}

Edit: current approach with Professors being stored in List&lt;Professors&gt; and two methods cheking if namd and surname exist

答案1

得分: 2

我假设你的 DProf 类中也包含了一个 Professor 类的列表。

接口 java.util.List 声明了方法 contains(Object)。该方法在列表中的某个对象等于方法参数时返回 true。类 java.lang.Object 中的方法 equals(Object) 用于确定两个对象是否相等。由于 Java 中的所有类都扩展自 Object 类,这意味着你的 Professor 类继承了该方法。然而,类 Object 中的方法 equals(Object) 是一种通用实现,因此不适用于你的 Professor 类。因此,你需要在 Professor 类中重写方法 equals(Object)

这是我修改过的 Professor 类的版本。

public class Professor {
    private String name;
    private String surName;
    private String department;

    public Professor(String name, String surName) {
        this(name, surName, null);
    }

    public Professor(String name, String surName, String department) {
        this.name = name;
        this.surName = surName;
        this.department = department;
    }

    public void setDepartment(String dept) {
        department = dept;
    }

    @Override
    public boolean equals(Object obj) {
        boolean areEqual = false;
        if (obj instanceof Professor) {
            Professor other = (Professor) obj;
            areEqual = name.equals(other.name) && surName.equals(other.surName);
        }
        return areEqual;
    }
}

按照你的要求,类 Professor 中的 equals() 方法在两个 Professor 实例的 namesurName 相同时返回 true

由于你提供的代码不是一个 最小可复现示例,我在代码中作了一些假设。这是我修改过的 DProf 类的版本。请参考代码后的注释。

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class DProf {
    private List<Professor> professors;
    String depName;

    public DProf(String name) {
        Objects.requireNonNull(name, "Null department name");
        depName = name;
        professors = new ArrayList<Professor>(); // 创建一个空的教授列表
    }

    public void addProfessor(Professor professor) {
        // 在此我希望检查新的教授实例的姓名和姓氏是否已存在于另一个实例中
        if (!professors.contains(professor)) {
            professor.setDepartment(depName);
            professors.add(professor);
        }
    }

    public static void main(String[] args) {
        DProf magic = new DProf("Sorcery");
        Professor prof = new Professor("Cuthbert", "Binns");
        magic.addProfessor(prof);
        prof = new Professor("Charity", "Burbage");
        magic.addProfessor(prof);
        prof = new Professor("Albus", "Dumbledore");
        magic.addProfessor(prof);
    }
}

我添加了一个名为 professors 的成员,因为我假设一个部门与多位不同的教授相关联。我假设初始情况下,教授尚未与部门关联,直到调用 addProfessor() 方法为止。因此,在 addProfessor() 方法中我也设置了教授的部门。我还添加了一个 main() 方法,仅用于允许我测试运行代码,以确保它成功运行。

英文:

I assume your DProf class also contains a List of Professors.

Interface java.util.List declares method contains(Object). The method returns true if the method argument equals one of the objects in the list. Method equals(Object), in class java.lang.Object is used to determine whether two objects are equal. Since all classes in java extend class Object, that means that your Professor class inherits that method. The implementation of method equals(Object) in class Object is a generic implementation and therefore not suitable for your Professor class. Hence you need to override method equals(Object) in class Professor.

Here is my modified version of class Professor.

public class Professor {
    private String name;
    private String surName;
    private String department;

    public Professor(String name, String surName) {
        this(name, surName, null);
    }

    public Professor(String name, String surName, String department) {
        this.name = name;
        this.surName = surName;
        this.department = department;
    }

    public void setDepartment(String dept) {
        department = dept;
    }

    @Override
    public boolean equals(Object obj) {
        boolean areEqual = false;
        if (obj instanceof Professor) {
            Professor other = (Professor) obj;
            areEqual = name.equals(other.name) &amp;&amp;  surName.equals(other.surName);
        }
        return areEqual;
    }
}

As you requested, method equals(), in class Professor, returns true if both Professor instances have the same name and surName.

Since the code in your question is not a minimal, reproducible example I made some assumptions regarding the code. Here is my modified version of your DProf class. See notes after the code.

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class DProf {
    private List&lt;Professor&gt; professors;
    String depName;

    public DProf(String name) {
        Objects.requireNonNull(name, &quot;Null department name&quot;);
        depName = name;
        professors = new ArrayList&lt;Professor&gt;(); // create an empty list of professors
    }

    public void addProfessor(Professor professor) {
        // Here I want to check if new Professor instance name and surname already exist in another instance of the object
        if (!professors.contains(professor)) {
            professor.setDepartment(depName);
            professors.add(professor);
        }
    }

    public static void main(String[] args) {
        DProf magic = new DProf(&quot;Sorcery&quot;);
        Professor prof = new Professor(&quot;Cuthbert&quot;, &quot;Binns&quot;);
        magic.addProfessor(prof);
        prof = new Professor(&quot;Charity&quot;, &quot;Burbage&quot;);
        magic.addProfessor(prof);
        prof = new Professor(&quot;Albus&quot;, &quot;Dumbledore&quot;);
        magic.addProfessor(prof);
    }
}

I added a member professors since I assume that a department has a number of different professors associated with it. I assume that initially, a professor is not associated with a department until you call the addProfessor() method. Hence I also set the Professor's department in the addProfessor() method. I also added a main() method simply to allow me to test run the code to make sure it runs successfully.

答案2

得分: 1

你可以像这样创建一个静态私有字段:

private static List<String> field = new ArrayList<>();

在添加教授之前,您可以检查 field.contains(name),但我认为可能存在更好的模式。

编辑:在调用教授的构造函数时将名称添加到您的列表中。

英文:

you can make a static private field like this :

private static list&lt;String&gt; field = new ArrayList();

and before you add a Professor you can check field.contains(name)

but i think some better pattern must exist

edit: and add the name in your list when you call the constructor of Professor

答案3

得分: 0

你可以在 Professor 类中添加一个 equals() 方法。

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Professor professor = (Professor) o;
        return Objects.equals(name, professor.name) &&
                Objects.equals(surName, professor.surName) &&
                Objects.equals(department, professor.department);
    }

然后你可以在 DProf 类内部初始化一个 List,并将创建的每个 Professor 对象添加到其中。

    class DProf {
        static List<Professor> profList = new ArrayList<>();
    
        public boolean addProfessor(Professor professor) {
            for (Professor someProf : profList) {
                if (professor.equals(someProf)) return false;
            }
            profList.add(professor);
            return true;
        }
    }

这样你就可以检查每个 Professor 对象是否与已有的对象匹配。

英文:

You could add a equals() method in Professor class.

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Professor professor = (Professor) o;
    return Objects.equals(name, professor.name) &amp;&amp;
            Objects.equals(surName, professor.surName) &amp;&amp;
            Objects.equals(department, professor.department);
}

Then you could initialize a List inside DProf class and add each Professor object you create inside it.

class DProf {
    static List&lt;Professor&gt; profList = new ArrayList&lt;&gt;();

    public boolean addProfessor(Professor professor) {
        for (Professor someProf : profList) {
            if (professor.equals(someProf)) return false;
        }
        profList.add(professor);
        return true;
    }
}

This way you could check whether each Professor object matches with already existing objects.

huangapple
  • 本文由 发表于 2020年9月11日 20:05:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63846759.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定