public static void main(String[] args) {
// 2)创建比较器对象
CompareWitnLength compareWitnLength = new CompareWitnLength();
// 3)将比较器对象传给TreeSet
TreeSet set = new TreeSet(compareWitnLength);
// 当默认排序和人工排序同时作用于一个类的时候,人工排序优先级高于默认的
set.add("java1");
set.add("java2");
set.add("java4");
set.add("java4");
set.add("java0");
System.out.println(set);
// 按照字符串的长短排序,长度相同再按字典排序
// 1.单独创建比较器对象,对应的类就是实现了Comparator接口的类,接口中有比较的方法叫compare(Object obj1,Object
// obj2)
// 2.将比较器对象作用去TreeSet,TreeSet里面再添加元素的时候,就会按照比较器规定的规则进行比较
//
ComWithAgeAndName comWithAgeAndName=new ComWithAgeAndName();
TreeSet set1 = new TreeSet(comWithAgeAndName);
set1.add(new Pp("bb1", 11));
set1.add(new Pp("bb2", 12));
set1.add(new Pp("bb3", 13));
set1.add(new Pp("bb4", 14));
set1.add(new Pp("bb4", 14));
set1.add(new Pp("bb5", 11));
System.out.println(set1);
}
}
// 1).创建字符串的比较器按照长短比较
class CompareWitnLength implements Comparator {
@Override
public int compare(Object arg0, Object arg1) {
if (!(arg0 instanceof String)) {
throw new ClassCastException();
}
if (!(arg1 instanceof String)) {
throw new ClassCastException();
}
String s1 = (String) arg0;
String s2 = (String) arg1;
int num = s1.length() - s2.length();
return num;
}
}
class Pp implements Comparable{
String name;
int age;
public Pp(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "P [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Object o) {
if(!(o instanceof P)) {
throw new ClassCastException();
}
P p=(P)o;
//例如先比较年龄,再比较姓名
int num = age - p.age;
return num==0?name.compareTo(p.name):num;
}
}
class ComWithAgeAndName implements Comparator {