类型不匹配:无法从PolarAngleComparator转换为Comparator <point>

时间:2017-10-05 03:49:51

标签: java comparator

public abstract class Sorter
{
     protected Comparator<Point> pointComparator;
     private Point lowestPoint;
     ...
     protected void setComparator()
     {
          if (condtion)
               pointComparator = new PolarAngleComparator(lowestPoint);
     }
 }
 public class PolarAngleComparator implements Comparator<Point>
 {
      private Point referencePoint;
      public PolarAngleComparator(Point p)
      {
           referencePoint = p;
      }        
      public int compare(Point p1, Point p2)
      {
         if(p1.equals(p2))
         {
             return 0;
         }
         else if (p1.equals(referencePoint) || !p1.equals(referencePoint) && 
         !p2.equals(referencePoint) && comparePolarAngle(p1, p2) == -1 ||
         !p1.equals(referencePoint) && !p2.equals(referencePoint) && 
         comparePolarAngle(p1, p2) == 0 && compareDistance(p2, p2) == -1)
         {
            return -1;
         }
         else
         {
            return 1;
         }
     }
  }

以下是我正在编写的代码。当我尝试将new PolarAngleComparator(lowestPoint)分配给pointComparator时,我的抽象类中出现的问题就出现了。抛出的错误是类型不匹配:无法从PolarAngleComparator转换为Comparator。我实现了Comparator,但是我仍然对为什么这个赋值会抛出错误感到困惑。任何有关这种情况/比较者的建议或知识都将受到赞赏。谢谢!

编辑:

public int comparePolarAngle(Point p1, Point p2) 
{
    if(crossProduct(p1, p2) == 0)
    {
        return 0;
    }
    else if(p1.equals(referencePoint) || crossProduct(p1, p1) > 0)
    {
        return -1;
    }
    else
    {
        return 1;
    }
}

    private int crossProduct(Point p1, Point p2)
{
    int p1x = (int) (p1.getX() - referencePoint.getX());
    int p1y = (int) (p1.getY() - referencePoint.getY());
    int p2x = (int) (p2.getX() - referencePoint.getX());
    int p2y = (int) (p2.getY() - referencePoint.getY());
    return ((p1x*p2y)-(p1y*p2x)); 
}

3 个答案:

答案 0 :(得分:0)

将您的班级定义为

public class PolarAngleComparator <Point> implements Comparator <Point>{
}

如果您不想在课堂上使用泛型,请将protected Comparator <Point> pointComparator;替换为protected Comparator pointComparator;

请务必查看https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

上的文档

答案 1 :(得分:0)

鉴于PolarAngleComparator构造函数下方的“三个点”代表compare()方法的实现(从界面中说明)。

public abstract class Sorter {
    protected Comparator<Point> pointComparator;
    private Point lowestPoint;

    protected void setComparator() {
        pointComparator = new PolarAngleComparator(lowestPoint);
    }
}

public class PolarAngleComparator implements Comparator<Point> {
    private Point referencePoint;

    public PolarAngleComparator(Point p) {
        referencePoint = p;
    }

    @Override
    public int compare(Point o1, Point o2) {
        return 0; //TODO: Implement comparator
    }
}

答案 2 :(得分:0)

您的代码编译得很好。你必须弄乱导入语句。确保您在两个地方都导入了相同的课程。