Java 集合Comparator接口

原文:https://www.studytonight.com/java/comparators-interface-in-java.php

在 Java 中,Comparator 接口用于以自己的方式对集合中的对象进行排序。它使您能够决定如何在集合和映射中对元素进行排序和存储。

Comparator接口定义compare()方法。这个方法有两个参数。此方法比较参数中传递的两个对象。如果两个对象相等,则返回 0。如果 object1 大于 object2,则返回正值。否则返回负值。如果对象类型不兼容,该方法可以抛出 ClassCastException 进行比较。


使用Comparator接口的规则

使用Comparator接口的规则:

  1. 如果要对集合的元素进行排序,需要实现 Comparator 接口。
  2. 如果您没有在Comparator接口中指定对象的类型,那么默认情况下,它假设您将对对象类型的对象进行排序。因此,当您覆盖 compare()方法时,您需要将参数的类型指定为“仅对象”。
  3. 如果要对用户定义的类型元素进行排序,那么在实现Comparator接口时,需要一般地指定用户定义的类型。如果在实现接口时没有指定用户定义的类型,则默认情况下,它采用对象类型,并且您将无法比较集合中的用户定义类型元素

例如:

如果您想根据学生类中定义的滚动数对元素进行排序,那么在实现Comparator接口时,您需要将其概括如下:

class MyComparator implements Comparator<Student>{}

如果你只写,

class MyComparator implements Comparator {}

然后,默认情况下,它假设 compare()方法参数的数据类型为 Object,因此您将无法比较 Student 类型(用户定义类型)对象。


是时候举个例子了!

学生班级:

class Student
int roll;
  String name;
  Student(int r,String n)
  {
      roll = r;
      name = n;
  }
  public String toString()
  {
      return roll+" "+name;
  }

MyComparator 类:

该类根据学生的成绩定义学生类的比较逻辑。学生对象将按卷的升序排序。

class MyComparator implements Comparator<Student>
{
  public int compare(Student s1,Student s2)
    {
        if(s1.roll == s2.roll) return 0;
        else if(s1.roll > s2.roll) return 1;
        else return -1;
    }
}

现在我们用main()函数创建一个 Test 类,

public class Test
{

   public static void main(String[] args)
   {
       TreeSet< Student> ts = new TreeSet< Student>(**new MyComparator()**);
       ts.add(new Student(45, "Rahul"));
       ts.add(new Student(11, "Adam"));
       ts.add(new Student(19, "Alex"));
       System.out.println(ts);
   }

}

[ 11 亚当,19 亚历克斯,45 拉胡尔]

如您在输出中所见,学生对象按照其滚动的升序存储。

注:

  • 当我们使用Comparator接口对集合中的元素进行排序时,我们需要传递实现Comparator接口的类对象。
  • 要对 TreeSet 集合进行排序,需要在 TreeSet 的构造器中传递该对象。
  • 如果使用了任何其他集合,比如 ArrayList,那么我们需要调用 Collections 类的 sort 方法,并将集合的名称和这个对象作为参数传递。
  • 例如,如果上述程序使用ArrayList集合,公共类测试如下:
public class Test
{
   public static void main(String[] args)
   {
       ArrayList< Student> ts = new ArrayList< Student>();
       ts.add(new Student(45, "Rahul"));
       ts.add(new Student(11, "Adam"));
       ts.add(new Student(19, "Alex"));
       Collections.sort(ts,new MyComparator()); /*passing the name of the ArrayList and the
object of the class that implements Comparator in a predefined sort() method in Collections
class*/
       System.out.println(ts);
   }
}