Collection类的Comparable

import java.util.*;


/**
 * Comparable 接口 是所有可以"排序"的类都是实现了java.lang.Comparable接口的 Comparable接口只有一个方法compareTo(Object o) jdk1.5使用泛型
 * public int compareTo(Object o) {
 *    this == o 返回0
 *    this > o 返回正数
 *    this <0 返回负数
 * }
 * 
 * 实现了compareTo() 从而确定该类的对象的排序方式
 * @author Administrator
 *
 */
public class TestComparable {
	
	public static void main(String []args) {
		
		List list = new ArrayList();
		list.add(new ComparableDemo("zhudansheng",120));
		list.add(new ComparableDemo("zhuxiaosheng",130)); 
		list.add(new ComparableDemo("John",1230)); 
		list.add(new ComparableDemo("Test",1330));
		
		System.out.println(list);
		
		Collections.sort(list);
		System.out.println(list);
	}
	
}

//实现comparable接口的类必须 重写equals和hashCode方法
class ComparableDemo implements Comparable{
	 private String name;
	 private int age;
	 
	 public ComparableDemo(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;
	}
	
	public boolean equals(Object o) {
		ComparableDemo comp = (ComparableDemo) o;
		if(comp instanceof ComparableDemo) {
			return this.name.equals(comp.name);
		}
		return super.equals(o);
	}
	
	public int hashCode() {
		return super.hashCode();
	}
	
	//比较对象的值,根据哈希码进行排序比较   使用compareTo() 方法对类的对象进行排序
	public int compareTo(Object o) {
		// TODO Auto-generated method stub
		 ComparableDemo comp = (ComparableDemo) o;
		 if(comp instanceof ComparableDemo) {
			  return  this.name.compareTo(comp.name);  //根据哈希表进行排序
			 // return rInt!=0 ? this.age>comp.age ? 1 : 0 : 0;
		 }
		 else {
			 return super.hashCode();
		 } 
	}
	
	public String toString() {
		return this.name +"  "+this.age;
	}
	 
}
 

你可能感兴趣的:(Collection)