JAVA之TreeSet中元素排序

TreeSet集合排序的两种方式

1、让元素自身具备比较性

也就是元素需要实现comparable接口,覆盖compareTo方法

这种方式也作为元素的自然排序,也可称为默认排序。

public class Cat implements Comparable {           //定义Cat类实现Comparable接口

	private String name;
	private int 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 Cat() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Cat(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	
	public int compareTo(Object o) {                            //重写Comparable接口的compareTo方法

		if (o instanceof Cat) {
			Cat cat=(Cat)o;
			if (this.getAge()>cat.getAge()) {
				return 1;
			} else {
				return -1;
			}
		}
		return 0;
	}
	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + "]";
	}
			
}

public class TreeSetTest {
	public static void main(String[] args) {
		TreeSet ts = new TreeSet();
		ts.add(new Cat("小白", 3));
		ts.add(new Cat("小白", 4));
		ts.add(new Cat("小白", 5));

		Iterator it = ts.iterator();
		while (it.hasNext()) {
			Object object = (Object) it.next();
			System.out.println(object);
		}
	}
}

2、让容器自身具备比较性,自定义比较器。

    当元素自身不具备比较性,或者元素自身具备的比较小不是所需的

那么这时只能让容器自身具备。

    定义一个类实现comparator接口,覆盖compare方法。

并将该接口的子类对象作为参数传递给treeset集合的构造函数。

public class MyComparator implements Comparator{
	public int compare(Object o1,Object o2) {
		Cat c1=(Cat)o1;
		Cat c2=(Cat)o2;
		
		if (c1.getAge()>c2.getAge()) {
			return -1;
		} else {
			return 1;
		}	
	}
}

public class Test2 {
	public static void main(String[] args) {
		TreeSet ts = new TreeSet(new MyComparator());   //创建TreeSet对象时传入自定义比较器
		
		ts.add(new Cat("小白", 9));
		ts.add(new Cat("小白", 2));
		ts.add(new Cat("小白", 4));

		Iterator it = ts.iterator();
		while (it.hasNext()) {
			Object object = (Object) it.next();
			System.out.println(object);
		}
	}
}
当Comparable比较方式,及Comparator比较方式同时存在,以Comparator比较方式为主。


猜你喜欢

转载自blog.csdn.net/amor_fatii/article/details/80186716
今日推荐