【问题标题】:Custom Sorting an array in java using Two values , x and y使用两个值x和y自定义java中的数组排序
【发布时间】:2018-01-21 16:15:13
【问题描述】:

我正在尝试根据x 值对数组进行排序,以防x 值相同,根据y 对其进行排序。在对打印的值进行排序后,我得到一个异常,我通过覆盖 Comparator 接口的 compare 方法来调用 compare 方法。

class coder
{
    int x,y,index;
}
public class CoderRating  implements Comparator<coder>{
    public int compare(coder A,coder B)
    {
        if(A.x==B.x)
        {
            if(A.y<B.y)
            return -1;
            else if(A.y>B.y)
            return 1;
            else
            return 0;
        }

        else if(A.x<B.x)
        return -1;

        else
        return 1;
    }

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        coder []c=new coder[n];

        for(int i=0;i<n;i++)
        {
            c[i]=new coder();
            c[i].x=sc.nextInt();
            c[i].y=sc.nextInt();
            c[i].index=i;
        }
        Arrays.sort(c);
        for(int i=0;i<n;i++)
        {
            System.out.println(c[i].x + "  "+c[i].y );
        }
    }

}

【问题讨论】:

  • 有什么问题?
  • 有什么异常? a\d 你从哪里得到的?
  • 你介意把coder class改成Coder class吗???如果你这样做我会很高兴的! ;-)(类名以大写开头)谢谢

标签: java arrays sorting comparator


【解决方案1】:

你调用了sort的错误重载,应该是:

Arrays.sort(c, new CoderRating());

目前,您正在调用 this sort 方法而不是 this,因此指定了您的比较器。

【讨论】:

    【解决方案2】:

    您没有使用已实现的Comparator 调用排序算法:

    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    coder []c=new coder[10];
    
    for(int i=0;i<n;i++)
    {
        c[i]=new coder();
        c[i].x=sc.nextInt();
        c[i].y=sc.nextInt();
        c[i].index=i;
    }
    Arrays.sort(c, new CoderRating()); //this is how it should be called
    for(int i=0;i<n;i++)
    {
        System.out.println(c[i].x + "  "+c[i].y );
    }
    

    输出:

    【讨论】:

      【解决方案3】:

      您在 coder 对象上调用 Arrays.sort 并且没有传递任何比较器对象,因此 Arrays.sort 正在 Coder 类中寻找可比较的对象。 2 个解决您问题的方法:

      1. 更改:在对编码器数组进行排序时传递所需的比较器。 将 Arrays.sort(c) 更改为 Arrays.sort(c,new CoderRating());

      2. 在编码器中实现可比性。重写 compareTo 方法,将 CoderRating 中 compare 方法的代码移动到 Coder 中的 compareTo 方法中。

      PS:为了您的代码清理:

      变化:

             `if(A.y<B.y)
                  return -1;
              else if(A.y>B.y)
                  return 1;
              else
                  return 0;`
      

      可以改为一根:

      return Integer.compare(A.y, B.y);

      输出:

      3 1 2 2 3 2 1 1 2 2 1 2 3

      【讨论】:

      • Integer.compare(A.y, B.y); 肯定会稍微减少代码,但如果您想尽可能深入地减少代码,那么甚至可以使用Arrays.sort(c, Comparator.comparingInt(coder::getX).thenComparingInt(coder::getY));,从而使CoderRating 类过时。
      猜你喜欢
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 2020-06-13
      • 2012-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多