[SOLVED] Strange behaviour by comparing EntityIds

I have a very strange behaviour I can not explain at all. Maybe it is just some Java related trickery I do not understand, I don’t know. Here the code

    private void updateEntity(Entity linked, Entity solved) {
        EntityId linkId = linked.get(Link.class).getLink();
        System.out.println("XXX LINKED " + linked);
        System.out.println("XXX SOLVED " + solved);
        System.out.println("YYY LINKID " + linkId + "==" + solved.getId());
        if (linkId == solved.getId()) {
            System.out.println("HEY HO!");
            solveQuests(linked, solved);
        }
    }

And the output is this

XXX LINKED Entity[EntityId[85], values=[Link[EntityId[86]], Quest[Power]]]
XXX SOLVED Entity[EntityId[86], values=[Solved, Solution[Power]]]
YYY LINKID EntityId[86]==EntityId[86]

I can not understand why the

        if (linkId == solved.getId()) {

is not true?! If it were true I would also see the “HEY HO!”
The only thing which works so far is

        if (linkId.equals(solved.getId())) {

I guess it then makes a string compare of the toString results of the both, a little backward if you ask me.

Can somebody explain me what is going on or what I do not see which is obvious to the rest of the world?!

Aaargh I guess I can answer the question my self. I did a instance compare I guess, if I do

        if (linkId.getId() == solved.getId().getId()) {

it works also as I here compare the long values. I guess it should be done that way.
Thanks for listening.

Yep, two different EntityId instances that just happened to share the same internal value.

Groovy would do the .equals() check and spoils you in these cases. :slight_smile:

So actually I should use equals method? Or counts this only for groovy? To be 100% sure I now use the Long value. But if equals also works and is the right choice I will use that. And in HasMaps? There I guess EntityId is fine, right?

I’m little confused …

EntityId has a proper .equals() method… yes, in general you should use it.

Groovy will automatically do .equals() when you use obj == obj… and then you get spoiled when you come back to Java.

Note: Java has an Objects utility class that will do the right thing for you:
if( Objects.equals(val1, val2) ) {
}

…it takes care of the null checks and so on.

1 Like