---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------
package heimaLog;
import java.util.*;
/*
*
* TreeSet:可以对Set集合按照自然顺序排序。
*
* 实现这种需求可以用两种方式完成:1,让对象自己具有可比性,实现Compareble接口
* 2,创建一个比较器,让集合本身具有比较性
* 当两种排序都存在存在时以比较器为主。
* 保证元素唯一性的依据是 compareTo方法返回0
*
* */
class Student implements Comparable<Student>{
private String name;
private int age;
Student(){}
Student(String name,int age){
this.name=name;
this.age=age;
}
public String getname(){
return name;
}
public int getage(){
return age;
}
public int compareTo(Student st){
if(this.age-st.age==0){
return this.name.compareTo(st.name);
}
return this.age-st.age;
}
}
class Px implements Comparator<Student>{
public int compare(Student s1,Student s2){
if(s1.getage()-s2.getage()==0){
return s1.getname().compareTo(s2.getname());
}
return s1.getage()-s2.getage();
}
}
public class TreeSetDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet ts = new TreeSet(new Px());
ts.add(new Student("zhangsan",22));
ts.add(new Student("lisi",21));
ts.add(new Student("wangwo",25));
ts.add(new Student("yangliu",18));
ts.add(new Student("yangliu",18));
Iterator it = ts.iterator();
while(it.hasNext()){
Student s = (Student)it.next();
sop(s.getname()+"_______"+s.getage());
}
}
public static void sop(Object obj){
System.out.println(obj);
}
}
47.---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------
黑马程序员-TreeSet排序学习日记 .
最新推荐文章于 2016-02-07 10:56:32 发布