1.首先我们先自定义一个比较器,实现Comparator接口,泛型传入自定义的比较器类对象,重写compare方法进行整体比较排序,在方法中返回比较的结果。
import java.util.Comparator;
//自定义一个比较器,让继承该类的子类整体排序
public class Animal implements Comparator<Animal>{
private double weight;
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
@Override
public int compare(Animal dog, Animal cat) {
return (int) (dog.getWeight() - cat.getWeight());
}
}
2.然后定义不同类型的子类对象,让它们继承自定义的比较器,并且实现Comparable接口,泛型传入自定义的比较器类对象,并重写compareTo方法,在方法中返回比较的结果,这里也可以返回0。
子类对象1
//让子类继承自定义的比较器Animal类,再实现Comparable接口,让子类排序
public class Cat extends Animal implements Comparable<Animal>{
private String name;
private double weight;
public Cat() {
super();
}
public Cat(String content) {
String[] data = content.split(",");
this.name = data[0];
this.weight = Double.valueOf(data[1]);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
@Override
public String toString() {
return "Cat [name=" + name + ", weight=" + weight + "]";
}
public int compareTo(Animal cat) {
return (int) (this.weight - cat.getWeight());
// return 0;
}
}
子类对象2
//让子类继承自定义的比较器Animal类,再实现Comparable接口,让子类排序
public class Dog extends Animal implements Comparable<Animal>{
private String type;
private double weight;
public Dog() {
super();
}
public Dog(String content) {
String[] data = content.split(",");
this.type = data[0];
this.weight = Double.valueOf(data[1]);
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
@Override
public String toString() {
return "Dog [type=" + type + ", weight=" + weight + "]";
}
public int compareTo(Animal dog) {
return (int) (this.weight - dog.getWeight());
// return 0;
}
}
3.写测试类
import java.util.TreeSet;
//测试TreeSet添加两个不同类型的对象 进行比较排序
public class TestTreeSet {
public static void main(String[] args) {
TreeSet<Animal> set = new TreeSet<Animal>(new Animal());
set.add(new Dog("柴犬,3.5"));
set.add(new Dog("柯基,7.5"));
set.add(new Dog("藏敖,5.5"));
set.add(new Cat("橘猫,6.5"));
set.add(new Cat("花猫,4.5"));
set.add(new Cat("胖猫,9.5"));
for (Object object : set) {
System.out.println(object);
}
}
}
4.测试结果:如:按照体重进行排序