首頁  >  文章  >  Java  >  Java中Comparable和Comparator怎麼使用

Java中Comparable和Comparator怎麼使用

WBOY
WBOY轉載
2023-05-03 10:07:061260瀏覽

Comparable 和 Comparator

Comparable 和 Comparator 是Java的兩個和排序相關的接口,又被稱為 自然排序和自訂排序。最近看了相關的內容,現在來記錄以下自己的學習狀況。
Comparable 和 Comparator 是關於排序的兩個接口,用來實作 Java 集合中的排序功能。具體作用可以查看 API 取得。

Comparable

這是API 文件中的簡短介紹:

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class’s natural ordering, and the class’s compareTo method is referred to as its natural comparison method. Compares this object with the specmified object for specrem. a positive integer as this object is less than, equal to, or greater than the specified object.

##用法:

需要排序實體類別的實作Comparable接口,並重寫compareTo() 方法,就可以具有排序功能。某些會自動對元素進行排序的集合(如 TreeSet),當把元素放入集合中,就會自動呼叫 CompareTo() 方法進行排序(前提是元素必須實作這個介面)。但是其他的地方也可以使用的,不只是局限於 TreeSet,使用還是很廣泛的。

Comparator

這是API 文件中的簡介:

A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of sort data struct struction maps), or to provide an ordering for collections of objects that don’t have a natural ordering.

用法:

Comparator 是一個第三方介面介面,具體用法是:設計一個比較器,建立一個類,實作這個接口,重寫compare() 方法。而由於 Comparator 是一個函數式接口,可以使用 Lambda 表達式來取代 Comparator 對象,使得程式碼更簡潔明了。

Talk is cheap, show me the code.

注意:博客中的內容可能不會很詳細,所以想看的具體細節的,應該以書本和官方文檔為主,這裡的內容更多的是簡單的介紹一下基本的用法。

測試實體類別:Dog

public class Dog implements Comparable<Dog>{
	private String name;
	private int age;
	
	public Dog(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "Dog [name=" + name + ", age=" + age + "]";
	}

	@Override
	public int compareTo(Dog dog) {
		return this.age > dog.age ? 1 : this.age < dog.age ? -1 : 0;
	}
}

#測試實體類別:Cat

public class Cat implements Comparable<Cat>{
	private String name;
	private Integer age;
	
	public Cat(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;
	}
	
	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + "]";
	}

	@Override
	public int compareTo(Cat o) {
		//可以直接调用,这样更简单
		//调换 o.age 和 this.age 就是相反的顺序
		return o.age.compareTo(this.age); 
	}
}

測試類:Test

public class Test {
	public static void main(String[] args) {
		List<Dog> dogs = new LinkedList<>();
		List<Cat> cats = new LinkedList<>();
		
		dogs.add(new Dog("大黄",6));
		dogs.add(new Dog("大白",1));
		dogs.add(new Dog("小黑",5));
		dogs.add(new Dog("旺财",3));
		dogs.add(new Dog("二哈",2));
		
		cats.add(new Cat("牛牛",3));
		cats.add(new Cat("花咪",4));
		cats.add(new Cat("咪咪",10));
		cats.add(new Cat("小黄",2));
		cats.add(new Cat("大橘",6));
		
		//参数为 null 使用 自然排序,否则使用 定制排序
		//也可以看出来 定制排序 优先级高于 自然排序
		System.out.println("---------自然排序 升序--------");
		dogs.sort(null);   
		dogs.forEach(System.out::println);
		System.out.println("---------自然排序 降序--------");
		cats.sort(null);
		cats.forEach(System.out::println);
		
		//定制排序
	    //Comparator<Dog> c = (e1,e2)->e2.getAge() - e1.getAge();
		//dogs.sort(c) 这个就是下面这个的具体形式,
		//可以看出来参数是一个 Comparator 对象  
		System.out.println("---------定制排序 降序--------");
		dogs.sort((e1,e2)->e2.getAge() - e1.getAge());
		//流式API的简单的应用,效果和上面的类似,或者直接使用 forEacn 循环遍历
		dogs.stream().forEach(System.out::println);
		System.out.println("---------定制排序 升序--------");
	//	另一种遍历方式,可以看出来函数式编程非常灵活,我也是初学,觉得很神奇。
		cats.stream()
		.sorted((e1,e2)->e1.getAge()-e2.getAge())
		.forEach(System.out::println);
	}
}

運行截圖:

Java中Comparable和Comparator怎麼使用

#補充說明:list.sort() 方法API 文件中的描述:

Sorts this list according to the order induced by the specified Comparator.

All elements in this list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the list). If the specified comparator is null then all elements in list). If the specified comparator is null then all elements in this list must imple the Comparable the elements’s natural ordering should be used. This list must be modifiable, but need not be resizable.

#可以看到,這個方法進行排序通過一個Comparator 對象,如果傳入參數為null的話,則會進行自然排序,但是注意:自然排序的前提是相應的實體類別實作了Comparable 接口,並重寫了compareTo() 方法。

以上是Java中Comparable和Comparator怎麼使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除