【发布时间】:2015-04-01 03:06:30
【问题描述】:
public class Test implements Comparable <Test>{
String name;
int age;
int salary;
public Test(String name, int age, int salary){
this.name = name;
this.age = age;
this.salary = salary;
}
public int compareTo(Test newTest){
if (this.name.compareTo(newTest.name) > 0){
return 1;
} else if(this.name.compareTo(newTest.name) < 0){
return -1;
} else{
return 0;
}
}
public static void main(String[] args){
Test Albert = new Test("Albert", 19, 100);
Test James = new Test("James", 16, 50);
if (Albert.compareTo(James) == -1){
System.out.println("Albert Comes first");
} else if (Albert.compareTo(James) == 1){
System.out.println("James Comes first");
} else{
System.out.println("It's a tie");
}
int[] testArray = new int[2];
testArray[0] = Albert.age;
testArray[1] = James.age;
Collections.sort(testArray, new TestComparator());
}
}
我创建了一个名为 TestComparator 的比较器,但由于某种原因它不适用于 Collections.sort。我不确定为什么它不起作用。有任何想法吗?我还尝试了 Array.sort ,但它不起作用。任何建议将不胜感激。
【问题讨论】:
-
你能把
TestComparator的代码贴出来吗?另外,请尝试指定您现在获得的输出是什么以及预期的输出是什么。 -
Test.compareTo()应该简单地返回name.compareTo(newTest.name)。它当然不应该两次调用name.compareTo()。 -
@aaa 我刚刚更新了我的答案,包括按名称排序和按年龄排序,两者都包含
Test对象列表。看看,让我知道它是否适合你。
标签: java arrays collections comparator