Do I need to override enum's hashCode() and equals()?

Hi all:
I have a enum type let's say it is
public enum Type
  ONE,
  TWO;
}If I want to compare the enum value to see if they are same value or not, let's say I have two:
Type a = Type.ONE;
Type b = Type.TWO;should I use a.equals(b) or (a == b) If I want to use it as another class's key field, and I want to override this class hashCode() and equals() methods.
Can enum Type return the correctly hash code?
For example the class is like:
public Class A
  Type type;
  pubilc boolean equals(Object other)
    // here skip check class type, null and class cast
    if(other.type.equals(this.type))
       return true;
    else
     return false;
  public int hashCode()
    int result = 31;
    result += 31 * result + type.hashCode() ;
   // can we get correct hash code from enum here?
    return result;
}

Answered by the test code by myself.
We can use either equals or (==) to see if they are the same value.
The enum's hashCode() use System.identityHashCode() to generate the hashCode and they are always correct

Similar Messages

  • Method Overriding-toString(),hashCode() and equals()?

    Hi,
    In some Java Classes, I saw that
    toString()
    hashCode()
    equals()
    these 3 methods of Object Class is overloaded.
    I don't understand why and in what situation we have to override these 3 methods of Object Class.
    Thanks in advance for ur Knowledge Sharing.
    Regards,
    S.Prabu

    toString() is typically overridden in subclasses so as to output something useful about a class like instance variable values instead of just a hashvalue representing the object reference as per Object.
    hashCode() and equals() are overridden typically for use within the collections framework though you need to fully understand the hashing contract before starting to override these as they can cause strange results if not overridden correctly.
    Take a look at collections and specifically the hashing functionality of HashMap and HashSet for more info on these.

  • When we override Hashcode and Equal Methods

    Hi....I have doubt regading Hashcode and equal methods
    why we override this two methods....
    why we override hashcode method when we are overriding equal method,
    i would very thankful to give answser
    Thank you
    Ramesh

    hash code is computed to check the equality of two
    objects ,
    that is why if u change the default equal method
    implementation , u need to change the hashcode method
    as well.That's an incomplete answer at best.
    The hashcode method is used by hashing algorithms and data strcutures such as HashMap. This value is used to determine what 'bucket' the reference will go into. It cannot, by itself determine equality.
    If you are still unsure, I suggest looking up 'hash table' on google. I'm sure there's a decent explanation on wikipedia.

  • Help need to know hashcode() and Equals method

    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........

    jverd wrote:
    euph wrote:
    jverd wrote:
    euph wrote:
    REFTY5_ wrote:
    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........Thery're asking you to override the equals and hashCode methods. Override means replace.So does "overwrite." However, as you point out, "override" is the correct word here.So you think "overwrite" means the same as "replace"?To the same extent that "override" does. But both are in the general sense. Override has a specific meaning in this Java context, and overwrite does not.Don't tell me. That's what I said in my original reply.
    To my ear it doesn't. To me "overwrite" means the original is destroyed, whereas when something is "replaced" the fate of the original is unknown. So I think there's a slight semantic difference between these words.Fair enough.Fair enougth, but the next time I suggest you're better sorted.

  • Use of hashCode and equals method in java(Object class)

    What is the use of hashCode and in which scenario it can be used?similarly use of equals method in a class when it overides form Object class. i.e i have seen many scenario the above said method is overridden into the class.so why and in which scenario it has to override?Please help me.

    You could find that out easily with google, that is a standard junior developer interview question.

  • Implementing hashcode and equals

    Is there anything more than performance reasons to always implement hashCode when you implement equals? If I understand correctly, when you put items in a hashtable it chooses the bucket by the hashcode and checks there is no equal item with the equals method. So it should still work if you never implement the hashcode method. But is there any other reason to implement hashCode than performance? Or have I just understood this completely wrong?

    Everything you say is true. And your example shows that point well. However, what if I just implement a hashCode that always returns 0? How will this work then? And does it have any differences than performance?
    Here is an example
    import junit.framework.*;
    import java.util.*;
    public class EqualsTest extends TestCase
      public void testHashCode()
        Map hashTable = new Hashtable();
        hashTable.put( new TestItem( 0 ), "0" );
        hashTable.put( new TestItem( 1 ), "1" );
        assertEquals( 2, hashTable.size() );
        Set hashSet = new HashSet();
        hashSet.add( new TestItem( 0 ));
        hashSet.add( new TestItem( 1 ) );
        assertEquals( 2, hashSet.size() );
      private class TestItem
        private final int i;
        public TestItem( int i )
          this.i = i;
        public boolean equals( Object o )
          final TestItem testItem = ( TestItem ) o;
          return i == testItem.i;
        public int hashCode()
          return 0;
    [/code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • SCJP 5.0 A question about hashcode() and equals()

    Here's an exercise from a book.
    Given:
    class SortOf {
    String name;
    int bal;
    String code;
    short rate;
    public int hashCode() {
    return (code.length()*bal);
    public boolean equals(Object o) {
    //insert code here
    Which of the following will fulfill the equals() and hashCode() contracts for this
    class? (Choose all that apply)
    A return ((SortOf)o).bal == this.bal;
    B return ((SortOf)o).code.length() == this.code.length();
    C return ((SortOf)o).code.length()*((SortOf)o).bal == this.code.length()*this.bal;
    D return ((SortOf)o).code.length()*((SortOf)o).bal*((SortOf)o).rate ==
    this.code.length()*this.bal*this.rate;
    C is a correct answer but D is also a correct answer according to the book writer,
    and I don't understand why.
    Normally, the rule is that if two objects are equals (according to the equals
    method)) then they must return the same hashcode. If we have two objects A and B;
    and A.bal == 2, A.code.length()==3, A.rate == 4 and B.bal == 4, B.code.length() ==
    3 and B.rate == 2. A and B are equals according with the D answer but they do not
    return the same hashcode.
    May someone help me make it clear?

    Generally ,the instance members decides the equals( ) & hashCode( ) contract . Here the code.length , bal fields are generating the hashCode.
    So it is appropriate to override the equals( ) method in such a way that , thonly those two fields wil decid the equality of the objects .
    Thanks,
    laksh.

  • Why do we need to override Hascode and Equals method?

    Hi,
    == checks if the two references are equal and .equlas will check if the value is same, if we want .equals to take care of both reference and value are correct. why cant I just override equals with an extra check that references are equal(==).
    Please someone elaborate on this and also tell me what role hashcode plays in this.
    thanks
    Anirudh

    anirudh1983 wrote:
    if we want .equals to take care of both reference and value are correct. why cant I just override equals with an extra check that references are equal(==).Many equals() methods do run an '==' check first for efficiency (and I would recommend it if you're writing one yourself).
    Please someone elaborate on this and also tell me what role hashcode plays in this.The reason that it is good practise to override equals() and hashCode() together is to maintain consistency.
    Hashcodes are used by all Java collections that contain the word 'Hash' in their name, and may also be used by other programs that need a hash code for identification; so if you supply one, you must follow the rules (which you can find in the API for Object.equals() and Object.hashCode()).
    The main rule is this: *objects that are equal() must have equal hashcodes*.
    Note that the reverse is NOT true: objects that are not equal() do not have to have different hashcodes, but it is usually better if they do.
    There is quite a lot to know about hashcodes, and what makes a good one, so I suggest you follow dcminter's advice if you want to be a happy and prosperous Java programmer.
    Winston

  • Help needed in overriding the finalize() method!

    Hi
    I need some help in overwriting the finalize() method.
    I have a program, but at certain points, i would like to "kill" a particular object.
    I figured that the only way to do that is to make that object's class override the finalize method, and call it when i need to kill the object.
    Once that is done, i would call the garbage collector gc() to hopefully dispose of it.
    Please assist me?
    Thanks
    Regards

    To, as you put it, kill an object, just null it. This
    will be an indication for the garbage collector to
    collect the object. In the finalizer, you marely null
    all fields in the class. Like this:
    public class DummyClass
    String string = "This is a string";
    Object object = new Boolean(true);
    public void finalize() throws Throwable
    super.finalize();
    string = null;
    object = null;
    public static void main(String[] args)
    //Create a new object, i.e allocate an
    te an instance.
    DummyClass cls = new DummyClass();
    //Null the reference
    cls = null;
    This is a pointless exercise. If an object is being finalized, then all the references it contains are about to cease being relevant anyway, so there's no purpose to be served in setting them to null.
    All that clearing a reference to an object does is to clear the reference. Whether the object is subsequently finalized depends on whether the object has become unreachable.
    Directly calling finalize is permitted, but doesn't usually serve any purpose. In particular, it does not cause the object to be released. Further, calling the finalize method does not consitute finalization of the object. Finalization occurs when the method is called as a consequence of a garbage collector action.
    If a variable contains a reference to an object (say a table), and you want a new table instead, then create a new table object, and assign its reference to the variable. Assuming that the variable was the only place that the old table's reference was stored, the old table will, sooner or later, get finalized and collected.
    Sylvia.

  • Help! Need to override Page Down/Page Up in JList

    Help! Need to override Page Down/Page Up in JList...
    PgUp PgDn selects the top or bottom item in a Jlist when JList is in focus. I want PgUp and PgDn to do something different (which it does), but it still selects top or bottom items. How do I COMPLETELY remove all key listeners in the JList?
    Oliver

    Sounds like you are just adding a key listener to the list and just
    listening for PAGE_UP/PAGE_DOWN. Which is why the original behavior is
    still there: both your listener and the list's own handler are being
    invoked.
    What you might want to do instead is to either set your own action
    for PAGE_UP/PAGE_DOWN in the list's input map, and then set that action
    to your own in the list's action map, or try setting the scrollUp and
    scrollDown actions to your own action in the list's action map. Note
    that shift PAGE_UP/PAGE_DOWN are also bound, by the way.
    : jay

  • I need to override a certificate error in version 31 - I don't see the old choice to add exception. How can I do this?

    I work in a test environment and need to override the security error in new version 31, but it does not seem to be available. How can I do this?
    Secure Connection Failed
    An error occurred during a connection to shopdeluxe-bnb.uat.deluxe.com. Issuer certificate is invalid. (Error code: sec_error_ca_cert_invalid)

    Options/Preferences > Advanced > Certificates > "Add Exception" is where you can add a local cert. There was also a new ca cert [https://blog.mozilla.org/security/2014/04/24/exciting-updates-to-certificate-verification-in-gecko/] If there are any issues please file a bug.
    [Self-signed certificates make your data safe from eavesdroppers, but say nothing about who the recipient of the data is. This is common for intranet websites that aren't available publicly. ] via [https://support.mozilla.org/en-US/kb/secure-connection-failed-error-message].
    This may be helpful as well: [https://support.mozilla.org/en-US/questions/1002237]

  • Can I call hashCode() into equals()

    Hi,
    I implemented a class MyObject that overrides the method hashCode() that respect the general contract and the resulting hashcode value is stored in a data member of my class MyObject.
    I also overrided the equals() that looks like this:
    public boolean equals(Object obj) {
    if (obj == null) return false;
    if (obj == this) return true;
    if (other instanceof MyObject == false) {
    return false;
    .... complex tests to check the equality that take a long time....
    To optimize the equals() I would like to do:
    public boolean equals(Object obj) {
    if (obj == null) return false;
    if (obj == this) return true;
    if (other instanceof MyObject == false) {
    return false;
    // use the hashCode, if different, no need to make the complex checks
    if (hasCodeValue_ != obj.hashCode()) {
    return false;
    .... complex tests to check the equality
    I think it should work because the hashCode is different when the objects are different, but I can't find any example of equals() implementation that uses the hascode(), is there any reason for that ? Thanks for your help, BR,
    Sebastien.

    Would you clarify for me please?
    Do you mean that the hashCode method will naturally be
    faster because something like String.hashCode() will
    return faster than String.equals(otherString) ?Equals methods usually require a few checks before they really start comparing things. They check to see if the objects are the same, they check to see of the object passed in was null, they check the type of the argument and then they cast it. Then they start comparing members and if any of their members are Objects there's more of that.
    Hashcode methods just go right at the values. And like you said, they can be cached in a lot of cases like String.
    Or do you mean that one should take care to write
    hashCode methods that are very fast?
    If the latter, I'd like to hear about how you make
    sure of that.Well, you could eliminate fields from the calculation but that might produce bad results. Generally, you just don't do a lot of complicated operations.

  • Implementation of equals, hashCode, and

    I am writing an RMI application where the implementation of the remote interface cannot extend UnicastRemoteObject because it already extends another class. So, I need to explicitly export the server object using UnicastRemoteObject.exportObject(server, 0);� no problem.
    Problem is I�ve read that in order to make the class behave as if it had extend UnicastRemoteObject, you must provide implementations for equals, hashCode, and toString. I�ve searched the world over for implementations of these methods equivalent to those found in UnicastRemoteObject� no luck so far.
    Could you help me out?
    I�ve found some code that I�ve listed below� Is it equivalent to the equals and hashCode method found in UnicastRemoteObject? What about toString()?
    public class RemoteDataServer extends LocalDataServer implements RemoteInterface{
        private Remote serverStub;
        public RemoteDataServer() throws IOException {
            super();
            //export remote object
            serverStub = UnicastRemoteObject.exportObject(this);
        public boolean equals(Object obj) {
            return (obj == this || serverStub.equals(obj));
        public int hashCode() {
            return serverStub.hashCode();
    //toString()???

    Hi,
    At book Effective Java by Joshua Bloch you can see some info
    overriding these members.
    See at http://java.sun.com/docs/books/effective/index.html
    Here is the toString()spec method from Object :
    Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
    The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
    getClass().getName() + '@' + Integer.toHexString(hashCode())
    but toString from class String simply returns the string contents of
    an object.
    Hope this help

  • I am unable to override the crop area and adjust the crop margins in Acrobat X Standard.

    When cropping in Acrobat X Standard, I am no longer able to override the crop area and make adjustments in Acrobat X Standard. All options are grayed-out.
    This seems to be a relatively new issue, but I'm not sure when I started having the problem. While use the tool frequently, it's not daily, but I'd say that this is within the past couple of weeks.
    I've scoured the settings. I've trolled message boards. I've checked for updates. I'm wondering if there's something I'm missing or if I need to do a full reinstall.
    I've inserted an image below showing the issue. (Changing the page range and/or units seems to make no difference. I tried that out of desperation.
    Thanks, folks!

    Wow!  All fixed.  I ran defaults delete -g which did not show immediate improvement, but then I rebooted.  I must admit I did a Safe Boot, just to throw in one other solution I had seen.  However, everything is back to normal.  Thanks very much.

  • [svn] 4069: Fix for - an inherited read-write property is reported as write-only if an overriding setter is present and getter is absent .

    Revision: 4069
    Author: [email protected]
    Date: 2008-11-11 12:24:53 -0800 (Tue, 11 Nov 2008)
    Log Message:
    Fix for - an inherited read-write property is reported as write-only if an overriding setter is present and getter is absent.
    Constructor for mxml files will now have the default comment "Constructor"
    Also fix for asdoc help details doesn;t show description
    QE Notes: Baselines need to be updated.
    Doc Notes: None
    Bugs: SDK-16091, SDK-17863
    tests: checkintests
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-16091
    http://bugs.adobe.com/jira/browse/SDK-17863
    Modified Paths:
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/AsClass.java
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/AsDocUtil.java
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/TopLevelClassesGenerator.ja va
    flex/sdk/trunk/modules/compiler/src/java/flex2/configuration_en.properties

    Well, running a Windows disk utility on a Mac drive ought to muck things up pretty well. I hope you have backups. If not I suggest you try to backup your files. Then do the following:
    Extended Hard Drive Preparation
    1. Boot from your OS X Installer Disc. After the installer loads select your language and click on the Continue button. When the menu bar appears select Disk Utility from the Installer menu (Utilities menu for Tiger or Leopard.)
    2. After DU loads select your hard drive (this is the entry with the mfgr.'s ID and size) from the left side list. Note the SMART status of the drive in DU's status area. If it does not say "Verified" then the drive is failing or has failed and will need replacing. SMART info will not be reported on external drives. Otherwise, click on the Partition tab in the DU main window.
    3. Set the number of partitions from the dropdown menu (use 1 partition unless you wish to make more.) Set the format type to Mac OS Extended (Journaled.) Click on the Options button, set the partition scheme to GUID (only required for Intel Macs) then click on the OK button. Click on the Partition button and wait until the volume(s) mount on the Desktop.
    4. Select the volume you just created (this is the sub-entry under the drive entry) from the left side list. Click on the Erase tab in the DU main window.
    5. Set the format type to Mac OS Extended (Journaled.) Click on the Options button, check the button for Zero Data and click on OK to return to the Erase window.
    6. Click on the Erase button. The format process can take up to several hours depending upon the drive size.
    Upon formatting completing quit DU to return to the installer. Install OS X. Afterwards you can restore your personal data files and reinstall your third-party software.
    In the future never attempt to use any Windows disk utilities to fix or diagnose a Mac formatted drive.

Maybe you are looking for

  • How to resolve a Lenovo PC that will not pass the Lenovo Splash screen with no access to Windows

    Here is my problem and here is the solution!!! My B540 Ideacentre would not pass the Lenovo splash screen. The only operational keys I had was F1 (BIOS) and F12 (BIOS options). F2 went to a light blue screen so no chance of even a one key recovery. W

  • How do I get Messages on my MBP to display older texts?

    I am looking to creat a pdf of text message conversation dating back to August. I can briing everything up on my iPhone by repeatedly selecting 'Load Erlier Messages', but on the application ("Messages") I can find no way to do this. Anyone know how

  • I can't transfer music to or from my iPhone 4s in iTunes.

    I have enough memory and the latest versions of iPhone and iTunes software. When I try to drag and drop, I get a red circle with a line through it. I can play songs on my PC but can't add or delete playlists from my phone in It

  • Adding an field in the Layout Selection for Transaction FS10n

    Dear Experts, I am facing a problem and expect your help on this.. <u><b>SCENARIO:</b></u>  After putting in the required values in the fields like the G/L Account, the fiscal year, company code, etc the transcation prompts you with an grid containin

  • List Padding in CSS Designer

    I'm trying to set up an unordered list as a navigation menu using CSS Designer. I've set the list-style-type to none, but when I try to use CSS Designer to set the padding for the UL to 0px, it works initially, but when I turn Live View off and then