comparable 接口:

  1. 问题:java.util.Collections 类中的方法 Collections.sort(List list) 是根据什么确定容器中对象的“大小”顺序的?

  2. java 中所有可以“排序”的类都实现了 java.lang.comparable 接口,Comparable 接口中只有一个方法:

    public int  compareTo(Object obj):在该方法中,

    返回   0, 表示 this == obj;

    返回 正数,表示 this > obj;

          返回 负数,表示 this < obj;

  3. 实现了 comparable 接口的类通过实现 compareTo 方法从而确定该对象的排序方式.

Demo_1:

class MyName implements Comparable<MyName>{
	private int age;
	public MyName(int age) {
		this.age = age;
	}

	@Override
	public int compareTo(MyName mn) {
		if(this.age>mn.age){
			return 1;
		}else if(this.age<mn.age){
			return -1;
		}else {
			return 0;
		}
	}
}
public class Test {
	public static void main(String[] args) {
		MyName m1 = new MyName(12);
		MyName m2 = new MyName(25);
		System.out.println(m1.compareTo(m2)); // 输出:-1
	}
}

 Demo_2:

import java.util.*;
class Name implements Comparable<Name>{
	private String firstName, lastName;
	public Name(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}
	public String getFirstName(){
		return firstName;
	}
	public String getLastName(){
		return lastName;
	}
	@Override
	public String toString() {
		return firstName+" "+lastName;
	}
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof Name){
			Name name = (Name)obj;
			return (getFirstName().equals(name.firstName)) && (getLastName().equals(name.lastName));
		}
		return super.equals(obj);
	}
	@Override
	public int hashCode() {
		return firstName.hashCode();
	}
	public int compareTo(Name objj) {
		int cmpResult = lastName.compareTo(objj.lastName);
		return  cmpResult !=0 ? cmpResult:firstName.compareTo(firstName);
	}
}
class Test {
	public static void main(String[] args) {
		LinkedList<Name> ln = new LinkedList<Name>();
		ln.add(new Name("song","bo"));
		ln.add(new Name("song","qi"));
		ln.add(new Name("song","ting"));
		ln.add(new Name("liu","bo"));
		ln.add(new Name("fang","qi"));
		ln.add(new Name("shang","qi"));
		ln.add(new Name("zhu","ting"));
		System.out.println(ln); // 输出:
		Collections.sort(ln);
		System.out.println(ln); // 输出:
	}
}
// 第1次输出: [song bo, song qi, song ting, liu bo, fang qi, shang qi, zhu ting]
// 第2次输出: [song bo, liu bo, song qi, fang qi, shang qi, song ting, zhu ting] 

 

  

posted on 2017-04-26 21:24  牧羊人的世界  阅读(736)  评论(0编辑  收藏  举报