自然排序:继承接口comparable
实现方法compareTo()
方法。
定制排序:实现接口comparator
的compare()
方法。
配置函数方法
public class Phone implements Comparable{
private int age;
private String name;
public Phone(){
}
public Phone(String name,int age){
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Object o) {
if(o instanceof Phone){
Phone phone = (Phone)o;
int compare = this.name.compareTo(phone.name);
if(compare != 0){
return compare;
}else{
return this.age - phone.age;
}
}else{
throw new RuntimeException("输入的类型不匹配");
}
}
}
使用方法
public class TestTreeSet {
// 自然排序
@Test
public void test1(){
TreeSet ts = new TreeSet();
/* ts.add(45);
ts.add(-8);
ts.add(95);
ts.add(0);*/
ts.add(new Phone("Tom",15));
ts.add(new Phone("Jack",15));
ts.add(new Phone("Bob",15));
ts.add(new Phone("Jerry",15));
ts.add(new Phone("Tom",23));
Iterator iterator = ts.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
// 定制排序。
@Test
public void test2(){
Comparator com = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof Phone && o2 instanceof Phone){
Phone p1 = (Phone)o1;
Phone p2 = (Phone)o2;
int compareP = p1.getName().compareTo(p2.getName());
if(compareP != 0){
return compareP;
}else{
return Integer.compare(p1.getAge(),p2.getAge());
}
}else{
throw new RuntimeException("输入的数据类型不匹配");
}
}
};
TreeSet ts = new TreeSet(com);
ts.add(new Phone("Tom",15));
ts.add(new Phone("Jack",15));
ts.add(new Phone("Bob",15));
ts.add(new Phone("Jerry",15));
ts.add(new Phone("Tom",23));
Iterator iterator = ts.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}