java.lang.Comparable

 org.apache.hadoop.io.WritableComparable<T> extends Writable, Comparable<T>

自寫Key時便用到了WritableComparable,於是追到這裏。下面的是轉載的東西,自己試了,簡單明瞭

此接口強行對實現它的每個類的對象進行整體排序。此排序被稱爲該類的自然排序,類的compareTo方法被稱爲它的自然比較方法。
實現此接口的對象列表(和數組)可以通過Collections.sort(和Arrays.sort)進行自動排序。實現此接口的對象可以用作有序映射表中的鍵或有序集合中的元素,無需指定比較器。
Comparable 完成一個整形數組的排序

import java.util.Arrays;


public class MyInteger implements Comparable<Object>{
		private int n;
		public MyInteger(int n) {
		this.n = n;
	}
		
	public int compareTo(Object o) {
		if (o instanceof MyInteger){
		   MyInteger mi = (MyInteger)o;
		   if (mi.n == this.n){
		    return 0;
		   }
		   else if (mi.n > this.n){
		    return 1;
		   }
		   else {
		    return -1;
		   }
		}
		else {
		   return -1;
		}
	}
	
	public static void main(String[] args) {
		int n = 10;
		MyInteger []mis = new MyInteger[n];
		for (int i = 0;i < mis.length; i++){
		   mis[i] = new MyInteger((int)(Math.random() * 100));
		}
		for (MyInteger m:mis){
		   System.out.print(m.n + "\t");
		}
		Arrays.sort(mis);
		System.out.println();
		for (MyInteger m:mis){
		   System.out.print(m.n + "\t");
		}
	}
}



 

實現了Comparable接口的類在一個Collection(集合)裏是可以排序的,而排序的規則是按照你實現的Comparable裏的抽象方法compareTo(Object o) 方法來決定的。

compareTo方法在Object中並沒有被聲明,它是java.lang.Compareable接口中唯一的方法。一個類實現了Compareable接口,就表明它的實例具有內在的排序關係(natural ordering)。如果一個數組中的對象實現了Compareable接口,則對這個數組進行排序非常簡單:Arrays.sort();對於存儲在集合中的Comareable對象,搜索、計算極值以及自動維護工作都非常簡單。一旦你的類實現了Compareable接口,它就可以跟許多泛型算法(generic algorithm)以及依賴於該接口的集合的操作實現進行協作,以小的努力得到強大的功能。Java平臺庫中的所有值類(value classes)都實現了Compareable接口。

compareTo的約定是:
  將當前這個對象與指定的對象進行順序比較,當該對象小於、等於或大於指定對象時,分別返回一個負整數、0或正整數,如果無法進行比較,則拋出ClassCastException異常。

import java.util.*;
public class EmployeeSortTest {

	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Employee[] staff = new Employee[3];
		staff[0] = new Employee("harry Hacker",35000);
		staff[1] = new Employee("carl cracke",75000);
		staff[2] = new Employee("tony Tester",38000);
		
		Arrays.sort(staff);//sort方法可以實現對對象數組排序,但是必須實現 Comparable接口
		
		for(Employee e: staff)
		System.out.println("id=" + e.getId() + " name=" + e.getName() +
		".salary=" + e.getSalary());
	}
	
}
	
class Employee implements Comparable<Employee>
{
	public Employee(String n,double s)
	{
		name = n;
		salary = s;
		Random ID = new Random();
		id = ID.nextInt(10000000);
	}
	public int getId()
	{
		return id;
	}
	public String getName()
	{
		return name;
	}
	
	public double getSalary()
	{
		return salary;
	}
	
	public void raiseSalary(double byPercent)
	{
		double raise = salary * byPercent / 100;
		salary += raise;
	}
	
	public int compareTo(Employee other)
	{
		if(salary < other.salary)//這裏比較的是什麼 sort方法實現的就是按照此比較的東西從小到大排列
		return -1;
		if(salary > other.salary)
		return 1;
		return 0;
	}
	private int id;
	private String name;
	private double salary;
}



 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章