Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing String valued fields in Drool 5.5

Tags:

drools

I have some puzzling issues when use Drools 5.5 final to compare String valued fields.

Essentially, I am trying to find if there are a pair of persons sharing the same name. The Person class looks like below:

public class Person {
  private String name;

  public String getName()      { return name; }
  public void setName(String n) { this.name = n; }
  public Person(String name)    { this.name = name;}
}

The rule that I try to trigger is :

rule "uniquePersonName"
when
    $p1: Person($n1: name)
    $p2: Person(this != $p1, name == $n1)
then
    System.out.println("Duplicated person name found : " + $n1 + " " + $p2.getName());
end

But it never got triggered. However, if I change it to :

when
    $p1: Person($n1: name)
    $p2: Person(this != $p1, name != $n1)

The system works as expected, in other words, it finds all the pairs where the persons have different names.

After digging deeper, I found if I changed the name field to be of type Integer, the original rule worked fine. That made me think it was because of some bug with String comparison. So with the name field defined as the String type, I tried:

  1. not (name == $n1)
  2. (name == $n1)
  3. name.toString() = $n1.toString()
  4. name == $p1.getName()

Unfortunately, none of them worked.

Finally, the only way I could get it behave is to write the rule as:

when
    $p1: Person($n1: name)
    $p2: Person(name == $n1)
    eval($p1!=$p2)

This made me think perhaps the problem is caused by a combination of how this works and how String comparison is done.

This is very basic feature and I would be surprised this is caused by a bug in Drools 5.5 final. But again, I could not see a way through. Can any of you help?

Thanks.

GW

like image 805
gwang Avatar asked May 21 '26 05:05

gwang


1 Answers

It turns out this != $p1 transforms to !this.equals($p1) under the hood, and in my code I have an auto-generated equals method (code not shown in the original post), which totally change the default comparison behavior. After removing that equals method, all worked as expected.

like image 134
gwang Avatar answered May 26 '26 19:05

gwang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!