TreeMap和TreeSet在排序时如何比较元素,Collections工具类中的sort()方法如何比较元素

TreeSet和TreeMap排序时比较元素要求元素对象必须实现Comparable接口

Collections的sort方法比较元素有两种方法:

元素对象实现Comparable接口

实体类Dog

 public class Dog implements Cloneable,Comparable<Dog> {

     private String name;
private String age; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Dog(String name, String age) {
super();
this.name = name;
this.age = age;
}
public Dog() {
super();
}
@Override
public String toString() {
return "Dog [name=" + name + ", age=" + age + "]";
} public Object clone() throws CloneNotSupportedException { return super.clone();
}
@Override
public int compareTo(Dog o) { return this.getName().compareTo(o.getName());
}
}

测试类

 public class Test {

     public static void main(String[] args) {
List<Dog> list = new ArrayList<Dog>();
Dog d1 = new Dog("cac", "11");
Dog d2 = new Dog("bac", "11");
Dog d3 = new Dog("aac", "11");
Dog d4 = new Dog("eac", "11");
list.add(d1);
list.add(d2);
list.add(d3);
list.add(d4);
// MyCompare mc = new MyCompare();
// Collections.sort(list,mc);
Collections.sort(list);
for (Dog dog : list) {
System.out.println(dog);
} }
}

结果:

Dog [name=aac, age=11]
Dog [name=bac, age=11]
Dog [name=cac, age=11]
Dog [name=eac, age=11]

自定义比较器,Collections.sort(List list,Comparator<T> compare),创建比较器类实现接口

 public class Test {

     public static void main(String[] args) {
List<Dog> list = new ArrayList<Dog>();
Dog d1 = new Dog("cac", "11");
Dog d2 = new Dog("bac", "11");
Dog d3 = new Dog("aac", "11");
Dog d4 = new Dog("eac", "11");
list.add(d1);
list.add(d2);
list.add(d3);
list.add(d4);
MyCompare mc = new MyCompare();
Collections.sort(list,mc);
for (Dog dog : list) {
System.out.println(dog);
} }
} class MyCompare implements Comparator<Dog>{ @Override
public int compare(Dog d1, Dog d2) {
String s1 = d1.getName();
String s2 = d2.getName();
if(s1.equals(s2))
return 0;
else {
return s1.compareTo(s2);
}
} }

结果:

Dog [name=aac, age=11]
Dog [name=bac, age=11]
Dog [name=cac, age=11]
Dog [name=eac, age=11]

上一篇:[转载]tensorflow中使用tf.ConfigProto()配置Session运行参数&&GPU设备指定


下一篇:kvm虚拟化学习笔记(十一)之kvm虚拟机扩展磁盘空间