欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

關(guān)于Java中Comparable 和 Comparator的用法

 更新時間:2023年04月06日 11:21:53   作者:CrazyDragon_King  
這篇文章主要介紹了關(guān)于Java中Comparable 和 Comparator的用法,Comparable 和 Comparator 是關(guān)于排序的兩個接口,用來實現(xiàn) Java 集合中的的排序功能,需要的朋友可以參考下

Comparable 和 Comparator

Comparable 和 Comparator 是Java的兩個和排序相關(guān)的接口,又被稱為 自然排序和定制排序。最近看了相關(guān)的內(nèi)容,現(xiàn)在來記錄以下自己的學(xué)習(xí)情況。
Comparable 和 Comparator 是關(guān)于排序的兩個接口,用來實現(xiàn) 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 specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

用法:

需要排序?qū)嶓w類的實現(xiàn) Comparable 接口,并重寫 compareTo() 方法,就可以具有排序功能。某些會自動對元素進行排序的集合(如 TreeSet),當(dāng)把元素放入集合中,就會自動調(diào)用 CompareTo() 方法進行排序(前提是元素必須實現(xiàn)這個接口)。但是其他的地方也可以使用的,不只是局限于 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 certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural ordering.

用法:

Comparator 是一個第三方接口,具體用法是:設(shè)計一個比較器,創(chuàng)建一個類,實現(xiàn)這個接口,重寫 compare() 方法。并且由于 Comparator 是一個函數(shù)式接口,可以使用 Lambda 表達式代替 Comparator 對象,使得代碼更加簡潔明了。

Talk is cheap, show me the code.

注意:博客中的內(nèi)容可能不會很詳細(xì),所以想看的具體細(xì)節(jié)的,應(yīng)該以書本和官方文檔為主,這里的內(nèi)容更多的是簡單的介紹一下基本的用法。

測試實體類: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) {
		//可以直接調(diào)用,這樣更簡單
		//調(dià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));
		
		//參數(shù)為 null 使用 自然排序,否則使用 定制排序
		//也可以看出來 定制排序 優(yōu)先級高于 自然排序
		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) 這個就是下面這個的具體形式,
		//可以看出來參數(shù)是一個 Comparator 對象  
		System.out.println("---------定制排序 降序--------");
		dogs.sort((e1,e2)->e2.getAge() - e1.getAge());
		//流式API的簡單的應(yīng)用,效果和上面的類似,或者直接使用 forEacn 循環(huán)遍歷
		dogs.stream().forEach(System.out::println);
		System.out.println("---------定制排序 升序--------");
	//	另一種遍歷方式,可以看出來函數(shù)式編程非常靈活,我也是初學(xué),覺得很神奇。
		cats.stream()
		.sorted((e1,e2)->e1.getAge()-e2.getAge())
		.forEach(System.out::println);
	}
}

運行截圖:

運行截圖

補充說明: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 this list must implement the Comparable interface and the elements’s natural ordering should be used. This list must be modifiable, but need not be resizable.

可以看到,這個方法進行排序通過一個 Comparator 對象,如果傳入?yún)?shù)為 null 的話,則會進行自然排序,但是注意:自然排序的前提是相應(yīng)的實體類實現(xiàn)了 Comparable 接口,并重寫了 compareTo() 方法。

總結(jié)

簡單了解了一下 Comparable 和 Comparator 接口的作用和簡單的使用方法,這里使用了一點 Lambda 表達式的知識,不過都只是很淺顯的知識,應(yīng)該不難理解(我也只是正在學(xué)習(xí)中,哈哈)。通過一個 Dog 類和 Cat 類進行講解,我覺得很好,首先它很容易理解,并且可以快速掌握簡單的使用方法(學(xué)習(xí)是漸進式的,要一直努力學(xué)習(xí)知識才行)。

到此這篇關(guān)于關(guān)于Java中Comparable 和 Comparator的用法的文章就介紹到這了,更多相關(guān)Comparable和Comparator的用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • String StringBuilder StringBuffer區(qū)別以及源碼分析

    String StringBuilder StringBuffer區(qū)別以及源碼分析

    string是C++標(biāo)準(zhǔn)庫的一個重要的部分,主要用于字符串處理??梢允褂幂斎胼敵隽鞣绞街苯舆M行string操作,同時,C++的算法庫對string類也有著很好的支持,并且string類還和c語言的字符串之間有著良好的接口
    2021-06-06
  • Java中避免NullPointerException的方法總結(jié)

    Java中避免NullPointerException的方法總結(jié)

    這篇文章主要介紹了Java中避免NullPointerException的方法總結(jié)的相關(guān)資料,需要的朋友可以參考下
    2017-07-07
  • Spring Boot中是如何處理日期時間格式的

    Spring Boot中是如何處理日期時間格式的

    這篇文章主要介紹了Spring Boot中是如何處理日期時間格式的,幫助大家更好的理解和學(xué)習(xí)spring boot框架,感興趣的朋友可以了解下
    2020-11-11
  • Java如何實現(xiàn)圖片的疊加與拼接操作

    Java如何實現(xiàn)圖片的疊加與拼接操作

    這篇文章主要介紹了Java如何實現(xiàn)圖片的疊加與拼接操作,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-11-11
  • Java中線程中斷的幾種方法小結(jié)

    Java中線程中斷的幾種方法小結(jié)

    在Java中,線程中斷是一種協(xié)作機制,它通過設(shè)置線程的中斷標(biāo)志位來通知線程需要中斷,本文主要介紹了Java中線程中斷的幾種方法小結(jié),具有一定的參考價值,感興趣的可以了解一下
    2023-12-12
  • Springboot公共字段填充及ThreadLocal模塊改進方案

    Springboot公共字段填充及ThreadLocal模塊改進方案

    這篇文章主要為大家介紹了Springboot公共字段填充及ThreadLocal模塊改進方案詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-11-11
  • IDEA安裝Leetcode插件的教程

    IDEA安裝Leetcode插件的教程

    這篇文章主要介紹了IDEA安裝Leetcode插件的教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-11-11
  • Spring加載加密的配置文件詳解

    Spring加載加密的配置文件詳解

    這篇文章主要為大家詳細(xì)介紹了Spring加載加密的配置文件,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-07-07
  • Java多線程中的Future類詳細(xì)解讀

    Java多線程中的Future類詳細(xì)解讀

    這篇文章主要介紹了Java多線程中的Future類詳細(xì)解讀,Future表示一個可能還沒有完成的異步任務(wù)的結(jié)果,針對這個結(jié)果可以添加Callback以便在任務(wù)執(zhí)行成功或失敗后作出相應(yīng)的操作,需要的朋友可以參考下
    2023-11-11
  • 淺談Spring bean 生命周期驗證

    淺談Spring bean 生命周期驗證

    本篇文章主要介紹了淺談Spring bean 生命周期驗證,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10

最新評論