TreeSet集合排序两种实现方式Comparable和Comparator比较

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

/**
 * TreeSet集合排序有两种方式,Comparable和Comparator区别:
 * 1:让元素自身具备比较性,需要元素对象实现Comparable接口,覆盖compareTo方法。
 * 2:让集合自身具备比较性,需要定义一个实现了Comparator接口的比较器,并覆盖compare方法,
 *   并将该类对象作为实际参数传递给TreeSet集合的构造函数。 第二种方式较为灵活。
 */
public class TreeSetDemo3 {
	public static void main(String[] args) {
		
		Teacher t1 = new Teacher(111L);
		Teacher t2 = new Teacher(222L);
		
		TreeSet<Teacher> teachers = new TreeSet<Teacher>();
		teachers.add(t1);
		teachers.add(t2);
		
		for (Iterator<Teacher> iter = teachers.iterator(); iter.hasNext();) {
			Teacher t =  iter.next();
			System.out.println(t.getId());
		}
		
		System.out.println("------------------------");
		
		Student s1 = new Student(123L);
		Student s2 = new Student(456L);					//让集合自身具备比较性,这种方式较灵活	
		TreeSet<Student> students = new TreeSet<Student>(new StudentComparator());	

		students.add(s1);
		students.add(s2);

		for (Iterator<Student> iter = students.iterator(); iter.hasNext();) {
			Student s = iter.next();
			System.out.println(s.getId());
		}
		
	}
}

/**
 * 采用实现Comparable接口重写compareTo方法的方式,让元素自身具备比较性
 * @author Administrator
 *
 */
class Teacher implements Comparable<Teacher>{
	private Long id;
	
	public Teacher() {
	}
	public Teacher(Long id) {
		this.id = id;
	}

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	
	@Override
	public int compareTo(Teacher o) {
		return (int) (this.id - o.getId());
	}
}

//学生类
class Student {

	private Long id;

	public Student() {
	}
	public Student(Long id) {
		this.id = id;
	}

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
}

/**
 * 自定义定义一个实现了Comparator接口的比较器,并覆盖compare方法
 */
class StudentComparator implements Comparator<Student> {
	@Override
	public int compare(Student o1, Student o2) {
		return (int) (o1.getId() - o2.getId()); // 根据升序排序
	}
}

你可能感兴趣的:(TreeSet集合排序两种实现方式Comparable和Comparator比较)