标签:
PresonDemo
package cn.stat.p5.person.demo; public class PresonDemo implements Comparable { private String name; private int age; /** * @param args */ 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 void outPrint() { System.out.println(this.age+".."+this.name); } public PresonDemo(String name, int age) { this.name = name; this.age = age; } //TreeSet();为空时,实列类内部比较器 @Override public int compareTo(Object o) { // TODO Auto-generated method stub PresonDemo p=(PresonDemo)o; if(p.age<this.age) return 1; if(p.age>this.age) return-1; return 0; } }
比较器CompartorbyName
/** * 根据名子比较返回顺序 */ package cn.stat.p6.arraylist.demo; import java.util.Comparator; import cn.stat.p5.person.demo.PresonDemo; /** * @author Administrator * */ public class CompartorbyName implements Comparator { /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare(Object o1, Object o2) { // TODO Auto-generated method stub PresonDemo p1=(PresonDemo)o1; PresonDemo p2=(PresonDemo)o2; int temp=p1.getName().compareTo(p2.getName()); return temp==0?p1.getAge()-p2.getAge():temp; } }
TreeSetDemo
package cn.stat.p6.arraylist.demo; import cn.stat.p5.person.demo.PresonDemo; import java.util.Iterator; import java.util.TreeSet; import java.util.ArrayList; public class TreeSetDemo { public static void main(String[] args) { TreeSet ts=new TreeSet(new CompartorbyName()); //比较器 ts.add(new PresonDemo("list1",2)); ts.add(new PresonDemo("list9",2)); ts.add(new PresonDemo("list7",2)); ts.add(new PresonDemo("list4",2)); ts.add(new PresonDemo("list5",2)); Iterator<PresonDemo> it=ts.iterator(); while(it.hasNext()) { PresonDemo p=(PresonDemo)it.next(); System.out.println(p.getName()+" "+p.getAge()); } } }
标签:
原文地址:http://www.cnblogs.com/zywf/p/4734694.html