Java比较器接口介绍和示例

2021年3月17日18:34:38 发表评论 767 次浏览

本文概述

比较器接口用于对用户定义的类的对象进行排序。比较器对象能够比较两个不同类的两个对象。以下函数将obj1与obj2比较

语法如下: 

public int compare(Object obj1, Object obj2):

假设我们有一个自己的类类型的数组/数组列表, 其中包含诸如rollno, name, address, DOB等字段, 并且我们需要根据Roll no或name对数组进行排序?

方法1:一种明显的方法是使用一种标准算法编写我们自己的sort()函数。该解决方案需要针对不同的标准(如纸卷编号和名称)重写整个分类代码。

方法2:使用比较器接口-比较器接口用于对用户定义类的对象进行排序。此接口存在于java.util包中, 并且包含2个方法compare(Object obj1, Object obj2)和equals(Object元素)。使用比较器, 我们可以根据数据成员对元素进行排序。例如, 它可能在rollno, 名称, 年龄或其他任何东西上。

用于对List元素进行排序的Collections类的方法用于通过给定的比较器对List的元素进行排序。

// To sort a given list. ComparatorClass must implement 
// Comparator interface.
public void sort(List list, ComparatorClass c)

Collections.Sort()如何工作?

在内部, Sort方法会调用要排序的类的Compare方法。为了比较两个元素, 它询问"哪个更大?" Compare方法返回-1、0或1以表示它小于, 等于还是大于另一个。它使用此结果来确定是否应将其交换用于其排序。

工作程序:

Java

// Java program to demonstrate working of Comparator
// interface
import java.util.*;
import java.lang.*;
import java.io.*;
  
// A class to represent a student.
class Student
{
     int rollno;
     String name, address;
  
     // Constructor
     public Student( int rollno, String name, String address)
     {
         this .rollno = rollno;
         this .name = name;
         this .address = address;
     }
  
     // Used to print student details in main()
     public String toString()
     {
         return this .rollno + " " + this .name +
                            " " + this .address;
     }
}
  
class Sortbyroll implements Comparator<Student>
{
     // Used for sorting in ascending order of
     // roll number
     public int compare(Student a, Student b)
     {
         return a.rollno - b.rollno;
     }
}
  
class Sortbyname implements Comparator<Student>
{
     // Used for sorting in ascending order of
     // roll name
     public int compare(Student a, Student b)
     {
         return a.name.compareTo(b.name);
     }
}
  
// Driver class
class Main
{
     public static void main (String[] args)
     {
         ArrayList<Student> ar = new ArrayList<Student>();
         ar.add( new Student( 111 , "bbbb" , "london" ));
         ar.add( new Student( 131 , "aaaa" , "nyc" ));
         ar.add( new Student( 121 , "cccc" , "jaipur" ));
  
         System.out.println( "Unsorted" );
         for ( int i= 0 ; i<ar.size(); i++)
             System.out.println(ar.get(i));
  
         Collections.sort(ar, new Sortbyroll());
  
         System.out.println( "\nSorted by rollno" );
         for ( int i= 0 ; i<ar.size(); i++)
             System.out.println(ar.get(i));
  
         Collections.sort(ar, new Sortbyname());
  
         System.out.println( "\nSorted by name" );
         for ( int i= 0 ; i<ar.size(); i++)
             System.out.println(ar.get(i));
     }
}

输出如下:

Unsorted
111 bbbb london
131 aaaa nyc
121 cccc jaipur

Sorted by rollno
111 bbbb london
121 cccc jaipur
131 aaaa nyc

Sorted by name
131 aaaa nyc
111 bbbb london
121 cccc jaipur

通过在内部compare方法中更改返回值, 你可以按所需的任何顺序排序。例如对于降序, 只需在上述比较方法中更改a和b的位置即可。

按多个字段对集合进行排序

在之前的文章中, 我们讨论了如何使用Comparable和Comparator接口在单个字段的基础上对对象列表进行排序, 但是, 如果我们需要按照多个字段(如first sort)对ArrayList对象进行排序, 根据学生姓名, 其次根据学生年龄排序。

下面是上述方法的实现:

Java

// Java program to demonstrate working of Comparator
// interface more than one field
  
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Comparator;
  
class Student {
  
     // instance member variables
     String Name;
     int Age;
  
     // parameterized constructor
     public Student(String Name, Integer Age) {
         this .Name = Name;
         this .Age = Age;
     }
  
     public String getName() {
         return Name;
     }
  
     public void setName(String Name) {
         this .Name = Name;
     }
  
     public Integer getAge() {
         return Age;
     }
  
     public void setAge(Integer Age) {
         this .Age = Age;
     }
  
     // overriding toString() method
     @Override
     public String toString() {
         return "Customer{" + "Name=" + Name + ", Age=" + Age + '}' ;
     }
  
     static class CustomerSortingComparator implements Comparator<Student> {
  
         @Override
         public int compare(Student customer1, Student customer2) {
  
             // for comparison
             int NameCompare = customer1.getName().compareTo(customer2.getName());
             int AgeCompare = customer1.getAge().compareTo(customer2.getAge());
  
             // 2-level comparison using if-else block
             if (NameCompare == 0 ) {
                 return ((AgeCompare == 0 ) ? NameCompare : AgeCompare);
             } else {
                 return NameCompare;
             }
         }
     }
  
     public static void main(String[] args) {
  
         // create ArrayList to store Student
         List<Student> al = new ArrayList<>();
  
         // create customer objects using constructor initialization
         Student obj1 = new Student( "Ajay" , 27 );
         Student obj2 = new Student( "Sneha" , 23 );
         Student obj3 = new Student( "Simran" , 37 );
         Student obj4 = new Student( "Ajay" , 22 );
         Student obj5 = new Student( "Ajay" , 29 );
         Student obj6 = new Student( "Sneha" , 22 );
  
         // add customer objects to ArrayList
         al.add(obj1);
         al.add(obj2);
         al.add(obj3);
         al.add(obj4);
         al.add(obj5);
         al.add(obj6);
  
         // before Sorting arraylist: iterate using Iterator
         Iterator<Student> custIterator = al.iterator();
  
         System.out.println( "Before Sorting:\n" );
         while (custIterator.hasNext()) {
             System.out.println(custIterator.next());
         }
  
         // sorting using Collections.sort(al, comparator);
         Collections.sort(al, new CustomerSortingComparator());
  
         // after Sorting arraylist: iterate using enhanced for-loop
         System.out.println( "\n\nAfter Sorting:\n" );
         for (Student customer : al) {
             System.out.println(customer);
         }
     }
}

输出如下:

Before Sorting:

Customer{Name=Ajay, Age=27}
Customer{Name=Sneha, Age=23}
Customer{Name=Simran, Age=37}
Customer{Name=Ajay, Age=22}
Customer{Name=Ajay, Age=29}
Customer{Name=Sneha, Age=22}


After Sorting:

Customer{Name=Ajay, Age=22}
Customer{Name=Ajay, Age=27}
Customer{Name=Ajay, Age=29}
Customer{Name=Simran, Age=37}
Customer{Name=Sneha, Age=22}
Customer{Name=Sneha, Age=23}

参考文献:

http://www.dreamincode.net/forums/topic/169079-how-collectionssort-is-doing-its-stuff-here/

http://www.lsbin.com/Comparator-interface-in-collection-framework

本文作者:

里沙卜·马希尔

。如果你喜欢lsbin并希望做出贡献, 那么你也可以写一篇文章并将你的文章邮寄到contribution@lsbin.org。请参阅lsbin主页上显示的文章并为其他Geeks提供帮助。如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请发表评论。

木子山

发表评论

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