Java Comparable

Java Comparable 常用於集合或陣列比較元素,提供了單一的排序序列,會影響原類別,即實際類別被修改,使用 Collections.sort(List) 方法對 Comparable 類型的元素進行排序, Comparable Learn Java 增加了範例及各種實作的操作方法,透過單元測試來驗證產出結果。

大於 o 傳回 1 。
等於 o 傳回 0 。
小於 o 傳回 -1 。

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

Comparable Learning Java

用於將相同類別的物件與該類別的實例進行比較,它為使用者定義類別的物件提供資料排序。該類別必須實作 java.lang.Comparable 介面來比較其實例,它提供了compareTo 方法,該方法採用該類別的物件的參數, Java Comparable Course 單獨測試一個程式、過程或方法,進行正確性驗證的測試。

Initialize Comparable

實作比較器方法,學習 Comparable 的操作及應用。

public static class Fruit implements Comparable<Fruit> {
	private String name;
	private double quantity;
	private int type;

	public Fruit(String name, double quantity, int type) {
		this.name = name;
		this.quantity = quantity;
		this.type = type;
	}

	public String toString() {
		ToStringBuilder builder = new ToStringBuilder(this, ToStringStyle.JSON_STYLE);
		builder.appendSuper(super.toString());
		builder.append("name", name);
		builder.append("quantity", quantity);
		builder.append("type", type);
		return builder.toString();
	}

	@Override
	public int compareTo(Fruit o) {
		int ret = this.name.compareTo(o.name);
		if (ret == 0)
			ret = Double.compare(this.quantity, o.quantity);
		return ret;
	}
}

List<Fruit> list = Arrays.asList(new Fruit("Mango", Double.MAX_VALUE, 1), new Fruit("Mango", -1, 3),
		new Fruit("Peach", 3, 1), new Fruit("Orange", 2, 1));
Collections.sort(list);
[{"name":"Mango","quantity":-1.0,"type":3}, {"name":"Mango","quantity":1.7976931348623157E308,"type":1}, {"name":"Orange","quantity":2.0,"type":1}, {"name":"Peach","quantity":3.0,"type":1}]

Java Comparable Tutorial