我有两个带有两个不同compareTo()方法的不同类。当我对list进行排序时,我希望它首先按age进行排序。但是,如果要对两个Fysiker进行排序,并且他们的年龄相同,那么我希望将其排序为“ year”,这是他们开始学习的年份。

在运行主类时,我将80 Fysiker放入列表中,对它们进行排序,然后打印。它们都是按年龄排序的,但不是按年份排序的(如果年龄相同)。

Edit1(为什么不是重复的):
我不能使用abstract解决此问题的原因(他们在此问题的重复标记版本中已完成),是因为我需要能够通过编写Human实例化Human humantest = new Human()

主班:

public class Main {
public static void main(String[] args) {

    ArrayList<Human> randomFysiker = new ArrayList<Human>();
    for (int j=0;j<80;j++) {

        Fysiker f = new Fysiker();
        randomFysiker.add(f);
}
    Collections.sort(randomFysiker);

    System.out.println(randomFysiker);
}


}


人类:

import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class Human implements Comparable<Human> {

int age;
String name;
List<String> people = Arrays.asList("A","B","C","D","E","F","G","H","I","J","K","L","M","N","P");
Random randomGenerator = new Random();

public Human(int myAge, String myName) {
    name = myName;
    age = myAge;
}

public Human() {
    this.age = randomAge();
    this.name = randomName();
        }

public int compareTo(Human o) {
    return this.age - o.age;
}

private int randomAge() {
    return randomGenerator.nextInt(100);
}

protected String randomName() {
    return people.get(randomGenerator.nextInt(people.size()));
}

public int getAge() {
    return this.age;
}

public String getName() {
    return name;
}

public String toString() {
    return "\nName: " + name + "\nAge: " + age + " yrs old\n";
}
}


Fysiker类别:

public class Fysiker extends Human {

private int year;

public Fysiker(int myAgeF, String myNameF, int myYearF) {
    this.name = myNameF;
    this.age = myAgeF;
    this.year = myYearF;
}

public Fysiker() {
    this.name = randomName();
    this.age = randomAge();
    this.year = randomYear();
}

public int compareTo(Fysiker o) {
    if (this.age - o.age != 0) {
        return super.compareTo(o);
    }
    else {
        return this.year - o.year;
    }
}

private int randomAge() {
    return 15 + randomGenerator.nextInt(86);
}

private int randomYear() {
    int yearfifteen = 2015 - age + 15;
    if (yearfifteen >= 1932 && 2015 >= yearfifteen){
        return randomGenerator.nextInt(age-14) + yearfifteen; //(max-min)=(yearfifteen+age-15+1)-(yearfifteen+1)
    }
    else {
        return 1932 + randomGenerator.nextInt(84);
    }
}

public int getYear(){
    return year;
}

public String toString() {
    return super.toString() + "Started Physics: " + String.format("F%02d", this.year%100) + "\n";
}
}

最佳答案

compareTo()类的Fysiker方法更改为:

public int compareTo(Human o) {
    if (this.age - o.age != 0) {
        return super.compareTo(o);
    }
    else {
        return this.year - ((Fysiker)o).year;
    }
}


因此,这将覆盖超类方法,因此将调用子类的方法(即Fysiker)。

09-27 11:05