[Basic Java Tutorial] (39) Common Class Libraries Lecture 9: Comparator——Explanation of Comparable and Comparator~

insert image description here

1️⃣ Comparator: Comparable

In the previous article, we have introduced arrays and array manipulation tool classes Arrays, and learned that arrays are actually divided into two types of usage: ordinary arrays and object arrays. Ordinary arrays can be directly sorted (call) sorting) according to the size relationship of the data, while object arrays store address data themselves, so it is impossible to implement sorting according to the size relationship. However, a method (object array sorting: ) is still overloaded in the class, which can directly Arrays.sortsort object Arraysarrays .sort()public static void sort(Object[] a)

But if you want to use sort()the method to sort, there must be a prerequisite: the class where the object is located must implement Comparablethe interface, otherwise an exception will occur when the code is executed ClassCastException. The interface Comparableis a kind of comparator, which is defined as follows.

public interface Comparable<T>{
    
    
	public int compareTo(T o);
}

ComparableThere is only one method defined in the interface , compareTo()which returns a inttype of data, and developers only need to return three results when overriding this method: 1(>0), -1(<0), 0(=0).

When explaining Stringthe operation method of the class, I have explained compareTo()the method. In fact, Stringthe class, class, Integeretc. all implement Comparablethe interface, that is to say, the object arrays of these classes can directly use Arrays.sort()the method to sort the object array.

//	范例 1: 实现对象数组排序
package com.xiaoshan.demo;

import java.util.Arrays;

class Book implements Comparable<Book>{
    
    	//实现比较器
	private String title;
	private double price;
	
	public Book(String title,double price){
    
    
		this.title = title;
		this.price = price;
	}

	@Override
	public String toString(){
    
    
		return "书名:"+this.title+",价格:"+this.price+"\n";
	}

	@Override
	public int compareTo(Book o){
    
    	// Arrays.sort()会自动调用此方法比较
		if (this.price > o.price){
    
    
			return 1;
		}else if (this.price < o.price){
    
    
			return -1;
		}else{
    
    
			return 0;
		}
	}
}

public class TestDemo{
    
    
	public static void main(String[] args) throws Exception{
    
    
		Book books []= new Book []{
    
    
			new Book("Java开发实战经典",79.8),
			new Book("JavaWEB开发实战经典",69.8),
			new Book("Oracle开发实战经典",99.8),
			new Book("Android开发实战经典",89.8)
		};
		Arrays.sort(books);                                                    //对象数组排序
		System.out.println(Arrays.toString(books));
	}
}

Program execution result:

[书名:JavaWEB 开发实战经典,价格:69.8
,书名: Java开发实战经典,价格:79.8
,书名:Android 开发实战经典,价格:89.8
,书名: Oracle开发实战经典,价格:99.8]

This program Bookimplements Comparablethe interface when the class is defined, which means that objects of this class can implement the sorting operation of the object array. When using the method in the main class , the method overridden Arrays.sort()by the class will be called automatically to judge the size relationship of the objects, so that they will be sorted according to the price from low to high.BookcompareTo()

There are two implementations of comparators in Java, among which Comparableis the most commonly used comparator interface. In actual development, as long as the object array is sorted, Comparablethe interface implementation must be given priority.

2️⃣ Comparator to the rescue: Comparator

The comparator implemented by Comparablethe interface is a common usage, but from another perspective, if you want to use the Comparablecomparator, it means that you must consider the sorting requirements when defining the class. But what if a certain class definition does not implement Comparablethe interface, but what should I do if the object array needs to be sorted when the class definition cannot be modified? For this reason, Java provides another comparator: interface Comparator(rescue comparator), which is defined as follows.

@FunctionalInterface
public interface Comparator<T>{
    
    
	public int compare(T o1, T o2);
	public boolean equals(Object obj);
}

Through the definition, it can be found that the Comparator" " annotation declaration is used on the interface @Functionallnterface, so this interface is a functional interface. This interface provides a compare()method, which returns three results: 1(>0), -1(<0), 0.

@FunctionallnterfaceSome friends may have doubts. If the " " annotation is used on the defined interface , then there should only be one abstract method in the interface. Why can two be defined here?

It should be noted that although Comparatortwo abstract methods are defined in the interface, the subclass only needs to override the method when overriding compare(), and equals()such a method Objectalready has a default implementation (address comparison) in the class, that is to say, Objectthe method in the class does not belong to the limited scope.

If you want to use Comparatorthe interface to implement the sorting operation of the object array, you also need to replace java.util.Arraysthe sorting method in the class. The object array sorting method is:

public static<T> void sort(T[] a, Comparator<? super T> c);
//	范例 2: 利用Comparator 接口实现对象数组排序—— 定义一个类,此类不实现比较器接口
package com.xiaoshan.demo;

class Book {
    
    
	private String title;
	private double price;
	
	public Book(){
    
    }
	public Book(String title, double price){
    
    
		this.title = title;
		this.price = price;
	}
	
	@Override
	public String toString(){
    
    
		return "书名:" + this.title + ",价格:" + this.price + "\n";
	}
	public void setPrice(double price){
    
    
		this.price = price;
	}
	public void setTitle(String title){
    
    
		this.title = title;
	}
	public double getPrice(){
    
    
		return price;
	}
	public String getTitle(){
    
    
		return title;
	}
}

Assume that Bookthere are no design requirements for ordering in the initial design of the class and cannot be changed. However, with the deepening of development, there is a requirement for sorting object arrays, so at this time, you can use Comparatorthe interface to Bookdesign a sorting rule class for the class: BookComparator.

class BookComparator implements Comparator<Book>{
    
    

	@Override
	public int compare(Book o1, Book o2){
    
    
		if (o1.getPrice() > o2.getPrice()){
    
    
			return 1;
		}else if (o1.getPrice() < o2.getPrice()){
    
    
			return -1;
		}else{
    
    
			return 0;
		}
	}
}

This program defines a BookComparatorcomparator program class, so Arrays.sort()an instantiated object of this class needs to be passed when using sort.

The following test uses the specified comparator to implement the sorting operation of the object array.

public class TestDemo  {
    
    
	public static void main(String[] args) throws Exception {
    
    
		Book[] books = new Book [] {
    
    
			new Book("Java开发实战经典",79.8),
			new Book("JavaWEB开发实战经典",69.8),
			new Book("'Oracle开发实战经典",99.8),
			new Book("Android开发实战经典",89.8)
		};
		Arrays.sort(books, new BookComparator());
		System.out.println(Arrays.toString(books));
	}
}

Program execution result:

[ 书名:JavaWEB 开发实战经典,价格:69.8,
书名:Java开发实战经典,价格:79.8,
书名:Android开发实战经典,价格:89.8,
书名:Oracle开发实战经典,价格:99.8 ]

Using Comparatoris not as Comparableconvenient as , so when using Arraysthe class to implement object sorting, you must explicitly set an instantiated object of the sorting rule class before you can normally complete the sorting function of the object array.

3️⃣ The difference between Comparable and Comparator

  • java.lang.ComparableInterfaces are implemented in the classes of objects being compared and are used to define a natural ordering between objects. It has a compareTo()method that compares the order of the current object with the parameter object. Classes that implement Comparablethe interface can directly use sorting algorithms (such as Arrays.sort()or Collections.sort()) for sorting.
  • java.util.ComparatorInterfaces are independent of the object classes being compared. It is used to create a single comparator object and implements compare()methods to define comparison logic between different objects. By providing a custom Comparatorobject, any object can be sorted, which is different from the object itself implementing Comparablethe interface. ComparatorInterfaces are typically used when you need to dynamically change the collation or compare objects of non-native classes.


Review the previous article (click to jump) :
"[Basic Java Tutorial] (38) Commonly Used Class Libraries Lecture 8: Array Operation Class——Analyze all the operation methods in the Arrays class, and unlock Java array operation skills~"

Continue reading the next article (click to jump) :
"[Basic Java Tutorial] (Forty) Common Class Libraries Lecture Ten: Reflection Mechanism—Concepts and Advantages and Disadvantages, Usage Methods and Underlying Principles~"

Guess you like

Origin blog.csdn.net/LVSONGTAO1225/article/details/131848594