【发布时间】:2016-03-02 04:20:28
【问题描述】:
我遇到的问题是使用 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)方法在主类中,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;
}
}
我的问题在于我尝试调用的测试类
Collections.sort((List<Point>) linkedList);
我收到错误“集合类型中的方法 sort(List) 不适用于参数 (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);
}
}
【问题讨论】:
-
发布您的测试代码。
-
那条语句(collection.sort)不是没有使用 compareTo 吗?我认为这是因为我没有把它作为比较器,即使在点类中我也实现了可比较的,覆盖了 comapreTO
标签: java collections comparator comparable