Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1017661
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T10:44:20+00:00 2026-05-16T10:44:20+00:00

Edit: Prepare my objects for the use within a HashMap. after reading a bit

  • 0

Edit: Prepare my objects for the use within a HashMap.

after reading a bit about how to generate a hash code, im kind of confused now. My (probably trivial) question is, how should I implement a hashCode method when I have one field that I could use? Can I use the fiels directly?
If I understand correctly, the values for hashCode must not change during the lifetime of an object, and I only have an ID filed that fits this, but I have read otherwhere, that one should not use ID…despide of that, how would a hashCode function based on this one (unique and not changing) value look like? The equals method is also based on the id only..

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T10:44:21+00:00Added an answer on May 16, 2026 at 10:44 am

    If your object is mutable, then it is acceptable to have its hash code change over time. Of course, you should prefer immutable objects (Effective Java 2nd Edition, Item 15: Minimize mutability).

    Here’s the hashcode recipe from Josh Bloch, from Effective Java 2nd Edition, Item 9: Always override hashCode when you override equals:

    Effective Java 2nd Edition hash code recipe

    • Store some constant nonzero value, say 17, in an int variable called result.
    • Compute an int hashcode c for each field:
      • If the field is a boolean, compute (f ? 1 : 0)
      • If the field is a byte, char, short, int, compute (int) f
      • If the field is a long, compute (int) (f ^ (f >>> 32))
      • If the field is a float, compute Float.floatToIntBits(f)
      • If the field is a double, compute Double.doubleToLongBits(f), then hash the resulting long as in above.
      • If the field is an object reference and this class’s equals method compares the field by recursively invoking equals, recursively invoke hashCode on the field. If the value of the field is null, return 0.
      • If the field is an array, treat it as if each element is a separate field. If every element in an array field is significant, you can use one of the Arrays.hashCode methods added in release 1.5.
    • Combine the hashcode c into result as follows: result = 31 * result + c;

    It would be correct to follow the recipe as is, even with just one field. Just do the appropriate action depending on the type of the field.

    Note that there are libraries that actually simplify this for you, e.g. HashCodeBuilder from Apache Commons Lang, or just Arrays.hashCode/deepHashCode from java.util.Arrays.

    These libraries allows you to simply write something like this:

    @Override public int hashCode() {
        return Arrays.hashCode(new Object[] {
            field1, field2, field3, //...
        });
    }
    

    Apache Commons Lang example

    Here’s a more complete example of using the builders from Apache Commons Lang to facilitate a convenient and readable equals, hashCode, toString, and compareTo:

    import org.apache.commons.lang.builder.*;
    
    public class CustomType implements Comparable<CustomType> {
        // constructors, etc
        // let's say that the "significant" fields are field1, field2, field3
        @Override public String toString() {
            return new ToStringBuilder(this)
                .append("field1", field1)
                .append("field2", field2)
                .append("field3", field3)
                    .toString();
        }
        @Override public boolean equals(Object o) {
            if (o == this) { return true; }
            if (!(o instanceof CustomType)) { return false; }
            CustomType other = (CustomType) o;
            return new EqualsBuilder()
                .append(this.field1, other.field1)
                .append(this.field2, other.field2)
                .append(this.field3, other.field3)
                    .isEquals();
        }
        @Override public int hashCode() {
            return new HashCodeBuilder(17, 37)
                .append(field1)
                .append(field2)
                .append(field3)
                    .toHashCode();
        }
        @Override public int compareTo(CustomType other) {
            return new CompareToBuilder()
                .append(this.field1, other.field1)
                .append(this.field2, other.field2)
                .append(this.field3, other.field3)
                    .toComparison();
        }
    }
    

    These four methods can be notoriously tedious to write, and it can be difficult to ensure that all of the contracts are adhered to, but fortunately libraries can at least help make the job easier. Some IDEs (e.g. Eclipse) can also automatically generate some of these methods for you.

    See also

    • Apache Commons Lang Builders
      • EqualsBuilder
      • HashCodeBuilder
      • ToStringBuilder
      • CompareToBuilder
    • Effective Java 2nd Edition
      • Item 8: Obey the general contract when overriding equals
      • Item 9: Always override hashCode when you override equals
      • Item 10: Always override toString
      • Item 12: Consider implementing Comparable
      • Item 2: Consider a builder when faced with many constructor parameters
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

EDIT: after discussing here click here i decided to use Francis Avila solution, it
I'm trying to edit an INSERT query using bindParam(). Here is my code. public
I have this partial code: if ($getRecords = $con->prepare(SELECT * FROM AUCTIONS WHERE ARTICLE_NO
EDIT 07/14 As Bill Burgess mentionned in a comment of his answer, this question
EDIT: I was an idiot. I simply had an image that was vertically long,
EDIT: See my answer below--> I am wanting to have a view that when
Edit (updated question) I have a simple C program: // it is not important
EDIT: iam using ajax to load text in my content that is why onload
Edit : Note that, as Daniel and latkin noted in an answer and a
EDIT : It turned out that this can only be done through an external

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.