import java.util.Arrays; public class Testtestestestetstestetste { public static void main(String[] args) { //使用Arrays类对数组元素进行排序(Comparable接口的应用)Comparable Comparable comparable Man[] msMans = { new Man(3,"a"),new Man(60,"b"),new Man(2,"c") }; Arrays.sort(msMans); System.out.println(Arrays.toString(msMans)); } //只要 引用类型数组 必须Comparable接口,重写compareTo class Man implements Comparable{ int age; int id; String name; } public Man(int age;int id;String name){ super(); this.age = age; this.name = name; } public String toString(){ return this.name; } //引用的不知道,也不好比较,手动比较年龄。 //因为没有统一性 Arrays类中也有compareTo public int compareTo(Object o){ Man man = (Man) o; if (this.age < man.age){ return -1; } if (this.age >man.age){ return 0; } } }错在哪里
时间: 2023-12-06 22:39:33 浏览: 30
这段代码有以下几处错误:
1. Man类的定义应该写在Testtestestestetstestetste类的内部,否则会出现“找不到符号Man”的编译错误。
2. Man类的定义中,应该将id属性定义为int类型而非String类型。
3. Man类的构造方法中,第二个参数应该是id而非age。
4. Man类的compareTo方法中,当this.age > man.age时应该返回1而非0。
下面是修改后的代码:
```
import java.util.Arrays;
public class Testtestestestetstestetste {
public static void main(String[] args) {
Man[] mans = { new Man(3, 1, "a"), new Man(60, 2, "b"), new Man(2, 3, "c") };
Arrays.sort(mans);
System.out.println(Arrays.toString(mans));
}
static class Man implements Comparable<Man> {
int age;
int id;
String name;
public Man(int age, int id, String name) {
super();
this.age = age;
this.id = id;
this.name = name;
}
public String toString() {
return this.name;
}
public int compareTo(Man man) {
if (this.age < man.age) {
return -1;
} else if (this.age > man.age) {
return 1;
} else {
return 0;
}
}
}
}
```