`
^佐依^
  • 浏览: 17255 次
  • 性别: Icon_minigender_2
  • 来自: 惠安
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

Comparable接口简单示例程序

 
阅读更多
import java.util.*;

class Person implements Comparable{
	private String name;
	private int age;
	private float score;
	
	public Person(String name,int age,float score){
		this.name = name;
		this.age = age;
		this.score = score;
	}

	public int compareTo(Object obj){
		Person p=(Person)obj;
		if(p.score>this.score){
			return 1;
		}else if(p.score<this.score){
			return -1;
		}else {
			if(p.age>this.age){
				return 1;
			} else if(p.age<this.age){
				return -1;
			} else {
				return 0;
			}
		}
	}

	public String toString(){
		return "姓名:"+this.name+",年龄:"+this.age+",成绩:"+this.score;
	}
}

public class AdvDemo03{
	public static void main(String args[]){
		//Person p[] = new Person[5];
		//p[0] = new Person("张三",20,96);
		//p[1] = new Person("李四",19,96);
		//p[2] = new Person("王五",19,97);
		//p[3] = new Person("赵六",21,78);
		//p[4] = new Person("孙七",20,80);

		//Arrays.sort(p);

		//for(Person person : p){
		//	System.out.println(person);
		//}

		Set s = new TreeSet();
		s.add(new Person("张三",20,96));
		s.add(new Person("李四",19,96));
		s.add(new Person("王五",19,97));
		s.add(new Person("赵六",21,78));
		s.add(new Person("孙七",20,80));

		Iterator iter = s.iterator();
		while(iter.hasNext()){
			System.out.println(iter.next());
		}
	}
}

 Comparable接口要实现 int compareTo(Object obj) 方法
Arrays.sort(Object[ ] obj) | TreeSet 都应实现该接口,否则会抛出ClassCastException异常

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics