java Comparator无法工作
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的比较器,由于某些原因,它不能用于集合。分类我不知道为什么它不起作用。有什么想法吗?我也试过数组。没用的那种。任何建议都将不胜感激
# 1 楼答案
Collections.sort()
使用List<Integer>
而不是数组Arrays.sort()
仅在需要升序的情况下与int[]
一起使用将数组更改为
Integer[]
类型,您应该能够使用使用Arrays.sort()
的Comparator
版本