Using == vs .equals() with Enums (i.e. DamageCause, EntityType)

Discussion in 'Plugin Development' started by ohtwo, Mar 13, 2013.

Thread Status:
Not open for further replies.
  1. Offline

    ohtwo

    Hey guys, so I've been wondering why this snippet of code:
    Code:
    if(e.getCause().equals(DamageCause.PROJECTILE)
    works instead of this one:
    Code:
    if(e.getCause()==DamageCause.PROJECTILE)
    I thought for enums, it was safe to use "==" and possibly more efficient based on how .equals() is written.

    EDIT: I am aware of how Strings need to use .equals() to check for equivalence. "==" checks to see if the reference is the same, while .equals() checks to see if the Objects are the same. However, with enums, I thought that you can't have multiple objects of the respective enums...if that makes any sense. If someone experienced in Java could explain or correct me on that as well, that'd be awesome.
     
  2. Offline

    chasechocolate

  3. Offline

    gomeow

    You can use ==
     
  4. They should both work just as fine, you should make a debug to be 100% sure that it's that code's fault... e.g.
    Code:
    System.out.print("equals: " + e.getCause().equals(DamageCause.PROJECTILE));
    System.out.print("==    : " + (e.getCause() == DamageCause.PROJECTILE));
    
    If one is true and other one is false then there's something we don't understand about Java going on =) But I highly doubt that, they'll either be both false or both true.
     
  5. Offline

    desht

    For enums, both == and .equals() work, but == is to be preferred. The article that chasechocolate linked to explains why.
     
  6. Offline

    ohtwo

    I'll retest it and get back to you guys with code if need be.

    So I figured out that != was the culprit. Or at least it didn't work the way I needed to. I basically wanted to say if the damage cause was anything but a projectile, do some action.
    Code:
    if(e.getCause()!=DamageCause.PROJECTILE)
    For some reason, the above snippet of code didn't work...

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 31, 2016
  7. != and == are both logic operators, they work the same way, != returns a opposite result...
    Also, using if( !(e.getCause() == DamageCause.PROJECTILE) ) is the exact same thing as using !=.

    You should stop guessing what is the culprit and start gathering some concrete data.
    Print your expressions's results because apparently you don't trust basic logic operators, printing them should show you that they work as expected.
     
Thread Status:
Not open for further replies.

Share This Page