重写比较和比较后,Collections.sort无法正常工作

时间:2016-03-02 04:20:29

标签: java collections comparator comparable

我遇到的问题是使用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;
  }
}

我的可比较(比较)方法在主类中,Point如下所示:

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;
  }

}

我的问题在Test类中,我尝试调用

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

我收到错误&#34;类型集合中的方法sort(List)不适用于参数(List<Point>&#34;

如果我采用自己的方法,我不明白它的来源或原因。

测试代码:

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);     

    }
}

2 个答案:

答案 0 :(得分:3)

  

import java.awt.Point;

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

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

或者你可以做到

  

import points.Point;

答案 1 :(得分:1)

正如其中一条评论所述,排序调用中对List的强制转换是多余的。听起来你正在使用除java.util.List之外的List类。检查你的进口。

如果没有,你应该发布你的测试代码。