在这里,您可以看到我想要对两个列表进行排序的主要方法:使用我的 sortAscending() 方法的人和动物。人们已经实现了 compareTo 方法,因此具有可比性并使用此方法。Animal 没有实现 compareTo 方法。如果对象不可比较,我想要做的是从我的 sortAscending 方法中抛出某种异常。我怎样才能做到这一点 ?
public class Main {
public static void main(final String[] args) {
ArrayList<Person> people = new ArrayList<Person>();
Person person1 = new Person("Jonas", 36);
Person person2 = new Person("Petras", 16);
people.add(person1);
people.add(person2);
ArrayList<Animal> animals = new ArrayList<Animal>();
Animal animal1 = new Animal("Cat", 3);
Animal animal2 = new Animal("Dog", 1);
animals.add(animal1);
animals.add(animal2);
System.out.println(Main.sortAscending(people));
System.out.println(Main.sortAscending(animals));
}
public static <T extends Comparable<? super T>> ArrayList<T> sortAscending(
final ArrayList<T> list) {
Collections.sort(list);
return list;
}
}
public class Person implements Comparable<Person> {
final String name;
final int age;
public Person(final String name, final int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return String.format("{name=%s, age=%d}", name, age);
}
@Override
public int compareTo(final Person person) {
return this.age < person.age ? -1 : this.age == person.age ? 0 : 1;
}
}
public class Animal {
String name;
int age;
public Animal(final String name, final int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return String.format("{name=%s, age=%d}", this.name, this.age);
}
}