Comparable接口实现自定义类排序



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 list =new LinkedList();
		
		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











你可能感兴趣的:(Comparable接口实现自定义类排序)