我有一个班级:
public class FootballPlayer() {
private int scoredGoals;
//... some other attributes and some getters and setters
}
我需要在我的drools文件中有一个规则来决定谁是两个comapred玩家之间更好的玩家。
我遇到的困难是如何比较同一类的两个对象?
非常感谢你!
答案 0 :(得分:1)
没有困难,只有一个小小的悬崖必须环游。
rule "A better scorer"
when
$f1: FootballPlayer( $score1; scoredGoals )
$f2: FootballPlayer( $score2; scoredGoals > $score1 )
then
System.out.println( $f2.getName() + " is better than " + $f1.getName() );
end
当然,两位球员可能并列:
rule "Two scorers with equal cpability"
when
$f1: FootballPlayer( $score1; scoredGoals )
$f2: FootballPlayer( this != $f1, $score2; scoredGoals == $score1 )
then
System.out.println( $f2.getName() + " and " + $f1.getName() + " are in the same class" );
end
注意确保第二个与第一个不相符的约束! (这是“悬崖”。)
您可能还对确定最佳状态的规则感兴趣:
rule "The best scorer"
when
$f1: FootballPlayer( $score1; scoredGoals )
not FootballPlayer( scoredGoals > $score1 )
then
System.out.println( $$f1.getName() + " is the best" );
end
答案 1 :(得分:0)
我建议的解决方案是实现类似的界面;那样你 将能够根据得分目标对球员名单进行排序。
public class FootballPlayer implements Comparable<FootballPlayer>
{
private int scoredGoals;
public FootballPlayer(int scoredGoals)
{
this.scoredGoals = scoredGoals;
}
public static void main(String... args)
{
FootballPlayer a = new FootballPlayer(10);
FootballPlayer b = new FootballPlayer(5);
FootballPlayer c = new FootballPlayer(15);
List<FootballPlayer> fps = new ArrayList<FootballPlayer>();
fps.add(a);
fps.add(b);
fps.add(c);
Collections.sort(fps);
for (FootballPlayer fp : fps)
{
System.out.println(fp);
}
}
@Override
public String toString()
{
return " -- " + scoredGoals;
}
@Override
public int compareTo(FootballPlayer o)
{
if (o == null)
{
return 1;
}
if (o.scoredGoals < this.scoredGoals)
{
return -1;
}
else if (o.scoredGoals > this.scoredGoals)
{
return 1;
}
else
{
return 0;
}
}
}