[英]Comparator Won't Work
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,它不起作用。 任何意见,将不胜感激。
Collections.sort()
使用List<Integer>
而不是数组。
如果要升序, Arrays.sort()
仅与int[]
一起使用。
将数组更改为Integer[]
类型,您应该能够使用使用Comparator
的Arrays.sort()
版本。
对于以上程序。 您只需要使用Arrays.sort(testArray);
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;
Arrays.sort(testArray); //You are just using int array so no need of Collections.sort
for(int temp: testArray){
System.out.println("Age :: " + temp);
}
//Collections.sort(testArray, new );
}
}
如果要对对象进行排序,则必须使用可比较的接口,该接口将根据您在override compareTo方法中实现的内容进行排序。
您可以从下面的链接中更好地了解可比和比较器。 Java对象排序示例(比较器和比较器)
代码行
Collections.sort(testArray, new TestComparator());
应该抛出编译错误,因为Collections类中没有这样的排序方法。
使用Arrays.sort(testArray)
代替; 它将以升序对数组进行排序。
顺便说一句,您打算通过传递TestComparator一系列谓词来做什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.