现在的位置: 首页 > 综合 > 正文

Comparable接口实现自定义类排序

2013年07月24日 ⁄ 综合 ⁄ 共 526字 ⁄ 字号 评论关闭

1.实现Comparable接口

2.覆盖comparaTo方法----用传来的参数和实例本身的属性去比

class Father implements Comparable
{
	public int age;
	String name;
	@Override
	public int compareTo(Object o) {
		
		Father f=(Father)o;
		int res=this.age-f.age;
		if(res!=0)
		{
			res=this.name.compareTo(f.name);
		}
		return res;
	}

3.Collections.sort(list);调用系统排序

public static void main(String[] args)
	{
		List<Father> list =new LinkedList<Father>();
		
		list.add(new Father(23, "f"));
		list.add(new Father(20, "a"));
		list.add(new Child(22, "z"));
		
		Collections.sort(list);
		
		for(int i=0;i<list.size();i++)
		{
			Father f=list.get(i);
			System.out.println(f);
		}
	}

抱歉!评论已关闭.