有个问题:如何将两个不同类的实例插入同一个Treeset里面并排序
实现方式有两种,一种是通过“实现接口”,另一种是“继承”
假设现在有两个类,Cat猫类(有name和weight两种属性)和Dog狗类(有type和weight两种属性),将Cat和Dog的实例对象,存入一个Treeset中,并以重量weight进行排序。
实现方法1:继承父类,子类使用compareTo实现插入和排序
- 定义父类Animal:
public abstract class Animal {
private int weight;
private String type;
private String name;
public int getWeight() {
return weight;
}
}
- 子类Cat和Dog继承Animal并实现Comparable接口:
实现Comparable接口后,再实现其compareTo方法,插入时,会调用该方法,并根据返回值的值(正负或0)判断出大小,然后进行排序
Cat类:
public class Cat extends Animal implements Comparable{
private String name;
private int weight;
public Cat(String name, int weight) {
this.name = name;
this.weight = weight;
}
public int compareTo(Object o) {
Cat c = (Cat) o;
return c.weight - this.weight;
}
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
", weight=" + weight +
'}';
}
}
Dog类:
public class Dog extends Animal implements