📌  相关文章
📜  如何避免在Java中的 TreeSet 中出现重复的用户定义对象?

📅  最后修改于: 2022-05-13 01:55:17.790000             🧑  作者: Mango

如何避免在Java中的 TreeSet 中出现重复的用户定义对象?

Java 中的 TreeSet 类是Java集合框架的一部分,它实现了 NavigableSet 接口,该接口提供了在 SortedSet 中导航的功能。 NavigableSet 进一步扩展了 SortedSet 接口,它提供了保持元素排序的功能。

由于 TreeSet 类实现了 NavigableSet 接口,因此它同时具有 NavigableSet 和 SortedSet 的特性。

TreeSet 根据自然顺序对元素进行排序或排序。所有的 Wrapper 类和 String 类都已经实现了 Comparable 接口。但是在自定义对象的情况下,必须在相应的类中实现 Comparable 或 Comparator 接口,以便 TreeSet 可以根据需要对对象进行排序。

带有用户定义对象的 TreeSet

当且仅当相应的类实现 Comparable 或 Comparator 接口时,才称对象是可比较的。 Comparator 接口的 compare() 方法和 Comparable 接口的 compareTo() 方法为 TreeSet 提供了排序逻辑,使 TreeSet 能够相应地插入值。现在,如果您想避免 TreeSet 中对象的任何重复条目,您必须使用相等性验证来实现这些接口我们可以通过多种方式做到这一点,

例子:

1. 使用可比较的界面:让我们制作一个学生类Student,其中包含学生姓名和学生在任何课程中的排名。在这里,同一排名的学生不能超过一名。因此,如果新条目的任何学生的排名之前已被其他学生占据,那么该条目将是重复条目。否则,学生将根据其姓名升序排序。

覆盖 compareTo() 方法以提供排序逻辑。在Comparable接口的compareTo()方法中,我们首先检查两个student对象的rank是否相同,如果相同则返回0,表示两个对象相同。否则,如果排名不同,则比较学生对象的名称并相应地返回 1 或 -1。

Java
// Java Program to Avoid Duplicate User
// Defined Objects in TreeSet
import java.util.*;
  
// implementing comparable interface
public class Student implements Comparable {
  
    private String name;
    private int rank;
  
    // constructor
    Student(String name, int rank)
    {
        this.name = name;
        this.rank = rank;
    }
  
    // returns the student name
    private String getName() { return name; }
  
    // returns student rank
    public int getRank() { return rank; }
  
    /*
      overriding compareTo() method.
      if the object has same rank then it is considered as a
      duplicate entry, else, the entry is sorted on the
      basis of the student name.
    */
    @Override public int compareTo(Student o)
    {
        if (rank == o.getRank()) {
            return 0;
        }
        else if (name.compareTo(o.getName()) < 0) {
            return -1;
        }
        else
            return 1;
    }
  
    // overriding toString() to print the student detail
    @Override public String toString()
    {
        return name + " (" + rank + ")";
    }
}
  
// driver class
class Gfg {
    
    public static void main(String args[])
    {
  
        // create a TreeSet which stores objects of type
        // Student
        TreeSet students = new TreeSet<>();
        
        // add objects to the TreeSet
        students.add(new Student("Raghav", 12));
        students.add(new Student("Tilak", 11));
        
        // adding an object with same rank
        students.add(new Student("Ayush", 12));
        
        // adding an object with same name but different
        // rank
        students.add(new Student("Raghav", 32));
        
        // print the TreeSet
        for (Student s : students) {
            System.out.println(s);
        }
    }
}


Java
// Java Program to Avoid Duplicate User
// Defined Objects in TreeSet
import java.util.*;
  
// implementing comparator interface
public class Employee implements Comparator {
  
    private String name;
    private int id;
  
    // constructor
    public Employee(String name, int id)
    {
        this.name = name;
        this.id = id;
    }
  
    // default constructor is required, since we have to
    // pass the instance of Comparator in the constructor,
    // while creating a TreeSet
    public Employee() {}
  
    // returns employee name
    public String getName() { return name; }
  
    // returns id of the employee
    public int getId() { return id; }
  
    /*
     overriding the compare() method, this method compare
     two objects of type Employee on the basis of their id,
     if the ids of two employees is same then its considered
     a duplicate entry. else, it is sorted of the basis of
     id.
    */
    @Override
    public int compare(Employee emp1, Employee emp2)
    {
        if (emp1.getId() == emp2.getId()) {
            return 0;
        }
        else if (emp1.getId() < emp2.getId()) {
            return -1;
        }
        else {
            return 1;
        }
    }
  
    // overriding toString() to print the employee detail
    @Override public String toString()
    {
        return name + " (" + id + ")";
    }
}
// driver class
class Gfg {
    public static void main(String args[])
    {
  
        // create a TreeSet which stores objects of type
        // Employee
        TreeSet employees
            = new TreeSet<>(new Employee());
        
        // add objects to the TreeSet
        employees.add(new Employee("Raghav", 934));
        employees.add(new Employee("Tilak", 435));
        employees.add(new Employee("Mumukshi", 252));
        
        // adding an object with same id
        employees.add(new Employee("Shalu", 934));
  
        // printing the TreeSet
        for (Employee s : employees) {
            System.out.println(s);
        }
    }
}


输出
Raghav (12)
Raghav (32)
Tilak (11)

2. 使用比较器接口:让我们创建一个具有员工姓名和员工 ID 的类 Employee。在这里,没有两个或多个员工可以拥有相同的 ID。员工根据他们的 id 进行排序。 (我们也可以在这个方法中实现与上面相同的逻辑)。在使用 Comparator 时,在创建一个 TreeSet 的构造函数中传递比较器的实例。这确保 TreeSet 以我们希望的方式排序,而不是按照 TreeSet 使用的自然排序。

Java

// Java Program to Avoid Duplicate User
// Defined Objects in TreeSet
import java.util.*;
  
// implementing comparator interface
public class Employee implements Comparator {
  
    private String name;
    private int id;
  
    // constructor
    public Employee(String name, int id)
    {
        this.name = name;
        this.id = id;
    }
  
    // default constructor is required, since we have to
    // pass the instance of Comparator in the constructor,
    // while creating a TreeSet
    public Employee() {}
  
    // returns employee name
    public String getName() { return name; }
  
    // returns id of the employee
    public int getId() { return id; }
  
    /*
     overriding the compare() method, this method compare
     two objects of type Employee on the basis of their id,
     if the ids of two employees is same then its considered
     a duplicate entry. else, it is sorted of the basis of
     id.
    */
    @Override
    public int compare(Employee emp1, Employee emp2)
    {
        if (emp1.getId() == emp2.getId()) {
            return 0;
        }
        else if (emp1.getId() < emp2.getId()) {
            return -1;
        }
        else {
            return 1;
        }
    }
  
    // overriding toString() to print the employee detail
    @Override public String toString()
    {
        return name + " (" + id + ")";
    }
}
// driver class
class Gfg {
    public static void main(String args[])
    {
  
        // create a TreeSet which stores objects of type
        // Employee
        TreeSet employees
            = new TreeSet<>(new Employee());
        
        // add objects to the TreeSet
        employees.add(new Employee("Raghav", 934));
        employees.add(new Employee("Tilak", 435));
        employees.add(new Employee("Mumukshi", 252));
        
        // adding an object with same id
        employees.add(new Employee("Shalu", 934));
  
        // printing the TreeSet
        for (Employee s : employees) {
            System.out.println(s);
        }
    }
}
输出
Mumukshi (252)
Tilak (435)
Raghav (934)