更改TreeSet的排序方式

TreeSet 的排序方式

讓元素本身具有比較性,需要實現Comparable接口
覆蓋compareTo方法

class Student   implements Comparable{    	//重寫compareto方法進行排序
	int age;
	String name;
	Student(String name,int age){
		this.name=name;
		this.age=age;
	}
	public String toString() {
		return name+age;
	}
	@Override
	public int compareTo (Object obj) {
		Student obj1=(Student)obj;
		int num=this.age-obj1.age;
		return num==0?this.name.compareTo(obj1 .name):num;
	}
	
	
}

public class TreeSetTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeSet<Student> set=new TreeSet<>();		

		set.add(new Student("fdk",21));
		set.add(new Student("hah",21));
		set.add(new Student("fdk",24));
		Iterator<Student> it=set.iterator();
		while(it.hasNext()){
			Student s=it.next();
			System.out.println(s);
		}
		
	}										

}



讓容器自身具有比較性 ,需要實現Comparator接口,覆蓋compare

public class TreeSetTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BySortage sort=new BySortage();	//重寫comparator排序
		TreeSet<Student> set=new TreeSet<>(sort);		

		
		set.add(new Student("fdk",21));
		set.add(new Student("hah",21));
		set.add(new Student("fdk",24));
		Iterator<Student> it=set.iterator();
		while(it.hasNext()){
			Student s=it.next();
			System.out.println(s);
		}
		
	}										

}
class BySortage implements Comparator<Student>{
	@Override
	public int compare(Student stu1, Student stu2) {
		int num=stu1.age-stu2.age;
		return num==0?stu1.name.compareTo(stu2.name):num;
	}
}
class Student   {    	
	int age;
	String name;
	Student(String name,int age){
		this.name=name;
		this.age=age;
	}
	public String toString() {
		return name+age;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章