Tes*_*lem 2 java comparable comparator
这似乎很奇怪,这不符合我的预期.我写了一个简单的java类,它实现了Comparable接口并覆盖了compareTo()方法.但是,它不允许我传递除Object之外的特定类型的参数.我查看了其他人的在线代码,他们使用了其他类型的对象,我将他们的代码复制到了eclipse中,但我仍然遇到了同样的错误.
我的问题是; 我要做的就是将这个对象与类型的对象进行比较让我们说.我对比较器接口(compare()方法)也有同样的问题.
这段代码是我在网上找到的.
public class Person implements Comparable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return this.age;
}
public String getName() {
return this.name;
}
@Override
public String toString() {
return "";
}
@Override
public int compareTo(Person per) {
if(this.age == per.age)
return 0;
else
return this.age > per.age ? 1 : -1;
}
public static void main(String[] args) {
Person e1 = new Person("Adam", 45);
Person e2 = new Person("Steve", 60);
int retval = e1.compareTo(e2);
switch(retval) {
case -1: {
System.out.println("The " + e2.getName() + " is older!");
break;
}
case 1: {
System.out.println("The " + e1.getName() + " is older!");
break;
}
default:
System.out.println("The two persons are of the same age!");
}
}
Run Code Online (Sandbox Code Playgroud)
}
Cod*_*der 12
您需要使用泛型来提供特定类型.
public class Person implements Comparable<Person> { // Note the generic to Person here.
public int compareTo(Person o) {}
}
Run Code Online (Sandbox Code Playgroud)
该Comparable接口的定义是这样的,
public interface Comparable<T> {
public int compareTo(T o);
}
Run Code Online (Sandbox Code Playgroud)
您可以利用泛型来使用自定义对象类型。更改您的类定义
public class Person implements Comparable {
Run Code Online (Sandbox Code Playgroud)
到
public class Person implements Comparable<Person> {
Run Code Online (Sandbox Code Playgroud)
现在您应该能够将 Person 对象传递给您的compareTo方法,如下所述:
@Override
public int compareTo(Person personToCompare){
Run Code Online (Sandbox Code Playgroud)
在此处了解有关泛型的更多信息:
https://docs.oracle.com/javase/tutorial/java/generics/types.html
| 归档时间: |
|
| 查看次数: |
3204 次 |
| 最近记录: |