Jump to content

== vs equals


Recommended Posts

Posted (edited)
20 hours ago, someguy567 said:

I'm wondering in this example, which would be more appropriate?


getGrandExchange().getStatus(GrandExchange.Box.BOX_1) == GrandExchange.Status.FINISHED_SALE

or


getGrandExchange().getStatus(GrandExchange.Box.BOX_1).equals(GrandExchange.Status.FINISHED_SALE)

 

One should make it a practice to always use #equals. Even when one is in a situation where references have to be compared (==) for a custom Class, one should still override the #equals method for it to implement reference comparing.

^ This does not apply to primitives and constants though :) .

Edited by Eagle Scripts
  • Like 1
Posted (edited)

Use == for primitives and constants
Use .equals() for everything else

GrandExchange.Status is an enum, and enum values are always constant (even if they for some reason are mutable), so here you should use '=='

15 hours ago, Alek said:

The following is not valid because String is an object:

String s = "abc";
 if(s == "abc") {
}

Those strings are literals actually; which are constant. '==' is valid :xboge:

Edited by FrostBug
  • Like 1
Posted
16 hours ago, FrostBug said:

Use == for primitives and constants
Use .equals() for everything else

GrandExchange.Status is an enum, and enum values are always constant (even if they for some reason are mutable), so here you should use '=='

Those strings are literals actually; which are constant. '==' is valid :xboge:

I think the main reason why what Alek wrote is valid is because both those string objects point to the same object. Compiler is smart enough to see that "abc" is being used twice and instead of making 2 separate objects, it makes both variables point to one "abc" object.

(90%)

Posted
8 hours ago, dreameo said:

I think the main reason why what Alek wrote is valid is because both those string objects point to the same object. Compiler is smart enough to see that "abc" is being used twice and instead of making 2 separate objects, it makes both variables point to one "abc" object.

(90%)

Yes, constants as in the same object. Java uses whats called a String constant pool where all string literals are stored. When creating the second literal, the pool is checked, and a reference to the previously added literal is returned

  • Like 1
  • Boge 1

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...