java comparator,实现Java Comparator

I am trying to write an algorithm which utilizes a min-priority queue, so I looked around on google and found the PriorityQueue. It seems that in order to use it, though, I am going to need to tell it how I want it to prioritize, and that the way to do this is with a comparator (I want to compare specific data fields of my "Node1" objects). More googling presented the idea of creating a new comparator which implements Comparator but overrides the compare method. What I am trying is this (and other variations of it as well):

import java.util.Comparator;

public class distComparator implements Comparator {

@Override

public int compare(Node1 x, Node1 y){

if(x.dist

return -1;

}

if(x.dist>y.dist){

return 1;

}

return 0;

}

}

The compiler protests on several grounds, one of which is that I haven't over-ridden the comparator class (which it says is abstract)

error: distComparator is not abstract and does not override abstract method compare(Object,Object) in Comparator

I have switched it to say "compare(object x, object y)", which takes care of that issue. At this point though the compiler complains that it can't find the "dist" variable in x or y--which makes sense, since they are part of my Node1 class, not the Object class.

So how is this supposed to work? It should have type Object, apparently, but then how do I direct it to the correct variable?

解决方案

You need to implement Comparator:

public class distComparator implements Comparator {

^^^^^^^

Without this, you are implementing Comparator, which isn't what you want (it can be made to work, but isn't worth the hassle).

The rest of the code in your question is fine, provided Node1 has an accessible member called dist.

Note that if you are using Java 7, the entire body of the method can be replaced with

return Integer.compare(x.dist, y.dist);

(replace Integer with Double etc, depending on the type of Node1.dist.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值