Java(Comparable排序接口)


Java(Comparable排序接口)
Java要保存數量不確定的數據,保存據有映射關系的數據(關聯數據),java提供了集合類。
集合類可以保存、盛裝其他數據,所以集合類也稱為容器類。全部的集合類都位於java.util包下。它和數組不一樣,數組既可以是基本類型的值,也可以是對象(真正保存的是對象的引用變量);而集合只能保存對象(只是保存對象的引用變量,簡單理解集合保存的是對象)

Comparable是排序接口。如果一個類實現Comparable接口,那么該類就支持 排序。實現了Comparable接口的類的對象的列表或數組可以通過Collections.sort或 Arrays.sort進行自動排序。
此外,實現此接口的對象可以用作有序映射中的鍵或有序集合中的集合,無需指 定比較器。
此接口只有一個方法compare,比較此對象與指定對象的順序,如果該對象小 於、等於或大於指定對象,則分別返回負整數、零或正整數。

public class fghjnfg {
	public static void main(String[] args){
		List persons = new ArrayList();
		persons.add(new Comparables(“一”, 3));//add新增元素
		persons.add(new Comparables(“二”, 2));
		persons.add(new Comparables(“三”, 2));
		persons.add(new Comparables(“四”, 1));
		persons.add(new Comparables(“五”, 3));
		persons.add(new Comparables(“六”, 3));
		persons.add(new Comparables(“七”, 4));
		···
		Collections.sort(persons);
		//使用迭代器遍歷輸出列表數據:Iterator
		//返回按適當順序在列表的元素上進行迭代的迭代器。
		Iterator iterator = persons.iterator();
		while (iterator.hasNext()) {//判斷是否有下一個元素
		Comparables persion = iterator.next();
		System.out.println(persion.getName()+"----"+persion.getAge());//輸出結果
		}
	}
}
// 首先實現接口Comparable
class Comparables implements Comparable {
	private int age;//這里定義成員變量
	private String name; //這里定義成員變量
	public Comparables() {//構造器
	}
	public Comparables(String name, int age){//有形參構造器
		this.name = name;
		this.age = age;
	}
	public int getAge() {
	return age;
	}
	public void setAge(int age) {
	this.age = age;
	}
	public String getName() {
	return name;
	}
	public void setName(String name) {
	this.name = name;
	}
	···
	//實現compareTo方法 o 表示和當前對象比較的另外一個對象
	public int compareTo(Comparables o) {
		// return this.age ‐ o.age;這里是ags年齡從小到大
		// 從小到大 :this‐o
		// 從大到小:o‐this
		//比較方法升級:先根據年齡排序,如果年齡一樣,根據姓名排序
		if (this.age!=o.age) {
		return this.age - o.age;
		} else {
		return this.name.compareTo(o.name);
		}
	}
}

結果截圖:
在這里插入圖片描述

注意:

小 於、等於或大於指定對象,則分別返回負整數、零或正整數。

// 從小到大 :this‐o
// 從大到小:o‐this


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM