TreeSet集合元素排序
TreeSet集合存储自定义对象:
默认需要实现Comparator,也可以通过比较器来实现,请看如下:
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetSummarize {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
operateObject();
}
public static void operateObject(){
TreeSet<Colleague> treeSet = new TreeSet<Colleague>(new cComparator());
Colleague colleague1 = new Colleague("xiashengbing", 32, "engineer");
Colleague colleague2 = new Colleague("lifenghong", 35, "manager");
Colleague colleague3 = new Colleague("yangwei", 29, "designer");
Colleague colleague4 = new Colleague("dongyuxing", 46, "outsourcing");
Colleague colleague5 = new Colleague("qingshan", 38, "executive");
treeSet.add(colleague1);
treeSet.add(colleague2);
treeSet.add(colleague3);
treeSet.add(colleague4);
treeSet.add(colleague5);
printTreeSet(treeSet);
}
public static void printTreeSet(TreeSet<Colleague> treeSet){
for (Iterator<Colleague> iterator = treeSet.iterator(); iterator.hasNext();) {
Colleague prisoner = iterator.next();
System.out.println(prisoner);
}
}
}
import java.util.Comparator;
import cn.itcast.list.Person;
class cComparator implements Comparator<Colleague>
{
@Override
public int compare(Colleague o1, Colleague o2) {
// TODO Auto-generated method stub
int num = o1.getPosition().compareTo(o2.getPosition());
if(num == 0)
{
return o1.getName().compareTo(o2.getName());
}
return num;
}
}
public class Colleague extends Person implements Comparable<Colleague>{
private String position;
public Colleague(String name, int age, String position) {
// TODO Auto-generated constructor stub
super(name, age);
this.setPosition(position);
}
@Override
public int compareTo(Colleague o) {
// TODO Auto-generated method stub
int num = this.getName().compareTo(o.getName());
if(num == 0)
{
return new Integer(this.getAge()).compareTo(new Integer(o.getAge()));
}
return num;
}
public void setPosition(String position) {
this.position = position;
}
public String getPosition() {
return position;
}
public String toString(){
return this.getName()+"..." + this.getAge() + "..." + this.position;
}
}