使用两个不同的对象

时间:2016-02-29 12:15:53

标签: java arrays sorting

我需要帮助排序包含我创建的两种不同类的数组。我的两个课程是"人类"有一个名字和一个年龄,然后我有一个班级"物理学家"从人类继承但也有领域"开始一年"当他们开始学习。像这样:

public class Human implements Comparable<Human> {

   private int age;
   private String name;

   public Human(int agein, String namein) {  
      age = agein;
      name = namein;   
   }
   public int compareTo(Human other) {

      return Integer.compare(this.age, other.age);       
   }
}

public class Fysiker extends Human {

   private int year;

   public Fysiker(int startYear, int ageIn, String nameIn){

       super(ageIn, nameIn);
       }

   public int compareTo(Fysiker other) {

       if(other instanceof Fysiker && this.getAge() == other.getAge() ) {
           return Integer.compare(this.year, other.year);
       }
       else {
           return Integer.compare(this.getAge(), other.getAge());
       }

   }
}

我想要的是,当我创建一个混合了人类和物理学家的阵列并对其进行排序时,我希望它按年龄排序,如果两个物理学家年龄相同,那么他们应该按照他们的年份排序。例如:

输入:

姓名:Alex,年龄:32岁,年份:2007

姓名:Nils,年龄:30岁,年份:2008

姓名:Anders,年龄:32岁,年份:2003

姓名:Erik,年龄:18岁。

姓名:Olof,年龄:31岁。

排序数组:

姓名:Erik,年龄:18岁。

姓名:Nils,年龄:30岁,年份:2008

姓名:Olof,年龄:31岁。

姓名:Anders,年龄:32岁,年份:2003

姓名:Alex,年龄:32岁,年份:2007

我的compareTo方法是错误的吗?或者为什么它不起作用? 我没有收到任何错误,数组只是按年龄排序,然后再也没有了。

我感谢你的帮助!

2 个答案:

答案 0 :(得分:1)

此方法:

public int compareTo(Fysiker other) {

    if(other instanceof Fysiker && this.getAge() == other.getAge() ) {
        return Integer.compare(this.year, other.year);
    }
    else {
        return Integer.compare(this.getAge(), other.getAge());
    }

}
永远不会调用

,因为你有一个Human数组,所以签名不匹配(如Arsen在评论中提到的那样)。

这应该有效:

public int compareTo(Human other) {

   if(other instanceof Fysiker && this.getAge() == other.getAge() ) {
       return Integer.compare(this.year, ((Fysiker) other).year);
   }
   else {
       return Integer.compare(this.getAge(), other.getAge());
   }

}

答案 1 :(得分:0)

除了实施Comparable之外,您还可以在排序时使用自定义Comparator。特别是对于Java 8,通过将Comparator.comparingComparator.thenComparing链接到自定义lambda函数,这对于比较多个字段也更加简单。

无论如何,Comparator(或Comparable)必须接受任何类型的Human,并检查它是否为Fysiker

List<Human> humans = Arrays.asList(
        new Fysiker(2007, 32, "Alex"),
        new Fysiker(2008, 30, "Nils"),
        new Fysiker(2003, 32, "Anders"),
        new Human(18, "Erik"),
        new Human(31, "Olof")
);
Collections.sort(humans, Comparator
        .comparing((Human h) -> h.age)
        .thenComparing((Human h) -> h instanceof Fysiker ? ((Fysiker) h).year : 0));
humans.forEach(System.out::println);

输出:

Human Erik 18
Fysiker Nils 30 2008
Human Olof 31
Fysiker Anders 32 2003
Fysiker Alex 32 2007