如何解决我总是在比较中返回 1,但我没有找到答案
import java.util.*;
public class S {
static Scanner sc = new Scanner(System.in);
static Integer a[] = new Integer[3];
public static void main(String[] args) {
int t = sc.nextInt();
while (t-- > 0) {
int n=3;
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
Arrays.sort(a,new Sort1());
}
}
}
class Sort1 implements Comparator<Integer>
{
public int compare(Integer a,Integer b)
{
for(int a1:S.a){
System.out.print(a1+" ");
}
System.out.println();
// return a-b;
return 1;
}
}
嗨可以解决我的问题。在java中比较tor如何工作? 输入: 1 5 2 7 输出 5 2 7 为什么输出不是 7 5 2? 如果我们返回 1 比,我会瘦什么。 1.5 2.5 2(因为一次返回)=>2 5 3.7 2 5=>7 5 2
解决方法
所以你对 Comparator
的理解是错误的。
从名称本身我们可以假设它需要比较一些东西对吗?但是在您的代码中,您没有进行任何比较,而是在比较器中打印了错误的值。
如果您检查比较器的参数,您会看到两个整数正在传递给它。这些整数实际上是您的数组元素。您需要比较这些元素。
public int compare(Integer a,Integer b)
{
if(a < b){
return 1;
}else if( a == b){
return 0;
}
else {
return -1;
}
}
像这样并在 main 中打印您的数组。它将被排序
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。