Collections.sort 重写 compare 和 compareTo 后不工作

Collections.sort not working after overriding compare and compareTo

我遇到的问题是使用 Collections.sort(linkedList);尝试对充满点的链表进行排序。我已经修改了 compare 和 compareTo 方法以满足需要。如此处发布的,此片段用于比较列表中的 Y 值,以便我们对它们进行排序。

 package points;

 import java.util.Comparator;

 public class CompareY implements Comparator<Point>
 {
    public int compare(Point p1, Point p2)
    {
         int equals = 0;

    if(p1.getY() > p2.getY())
    {
        equals = 1;
    }
    else if(p1.getY()< p2.getY())
    {
        equals = -1;
    }
    else if(p1.getY() == p2.getY())
    {
        //If the 'Y's' are equal, then check the 'X's'
        if(p1.getX() > p2.getX())
        {
            equals = 1;
        }
        if(p1.getX() < p2.getX())
        {
            equals = -1;
        }
    }
    return equals;
  }
}

我的比较(compare)方法主要在class内,点如图:

package points;

public class Point implements Comparable<Point>
{
    int x;
    int y;

public Point()
{
    //Blank default constructor
}
public Point(int x, int y)
{
    this.x = x;
    this.y = y;
}


//Auto generated getters and setters
public int getX() {
    return x;
}
public void setX(int x) {
    this.x = x;
}
public int getY() {
    return y;
}
public void setY(int y) {
    this.y = y;
}

public int compareTo(Point o)
{
    int equals = 0;

    if(this.getX() > o.getX())
    {
        equals = 1;
    }
    else if(this.getX() < o.getX())
    {
        equals = -1;
    }
    else if(this.getX() == o.getX())
    {
        //If the 'X's' are equal, then check the 'Y's'
        if(this.getY()> o.getY())
        {
            equals = 1;
        }
        if(this.getY() < o.getY())
        {
            equals = -1;
        }
    }
    return equals;
  }

}

我的问题出在测试 class 中,我尝试调用

Collections.sort((List<Point>) linkedList);

我收到错误 "The method sort(List) in the type Collections is not applicable for the arguments (List<Point>"

我不明白它是从哪里来的,或者如果我用我的方法它为什么会在那里。

测试代码:

package points;
import java.util.*;
import java.awt.Point;
public class Test
{

public static void main(String[] args) 
{
    Random rand = new Random();
    int sizeLimit = 10;

    LinkedList<Point> linkedList = new LinkedList<Point>();

    //Populating our linkedList with random values.
    for(int i=0; i < sizeLimit; i++)
    {
        linkedList.add(new Point(rand.nextInt(10), rand.nextInt(10)));
    }

    System.out.println("original list");

    //Declaring our iterator to step through and print out our elements
    Iterator<Point> iter = linkedList.iterator();
    while(iter.hasNext())
    {
        System.out.println(iter.next());
    }

    Collections.sort((List<Point>) linkedList);     

    }
}

如评论之一所述,在排序调用中强制转换为 List 是多余的。听起来您使用的列表 class 而不是 java.util.List。检查您的导入。

失败你应该post你的测试代码。

import java.awt.Point;

您正在导入错误 Point class。该代码现在不使用您的代码。

如果删除该行,您将从当前包中获得 Point class。

或者你也可以

import points.Point;