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 8317405
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T21:35:27+00:00 2026-06-08T21:35:27+00:00

i overrided hashCode() and equals() in a class (Dog) in order to store and

  • 0

i overrided hashCode() and equals() in a class (Dog) in order to store and retrieve it’s instances from a hashMap, the code is as follows:

class Dog {

public Dog(String n) {
    name = n;
}
public String name;

public boolean equals(Object o) {
    if ((o instanceof Dog)
            && (((Dog) o).name == name)) {
       return true;
    } else {
       return false;
    }
}

public int hashCode() {
    return name.length();
   }
}

and the hashMap code is as follows:

public class MapTest {

public static void main(String[] args) {
    Map<Object, Object> m = new HashMap<Object, Object>();
    m.put("k1", new Dog("aiko"));
    Dog d1 = new Dog("clover");
    m.put(d1, "Dog key");    // #1
    System.out.println(m.get("k1"));
    String k2 = "k2";
    d1.name = "arthur";     // #2
    System.out.println(m.get(d1)); #3 
    System.out.println(m.size()); 
  }
}

the problem is that, at 2 i changed the name of the dog object that’s stored inside the hashMap at 1, the expected output at 3 is NULL but the actual is Dog Key!! i expect it to fail in the equals() method as clover!=arthur but it succeds!! i noticed that when the hashCode succeds (i.e. the lengh==6) the value stored in the map is retrieved even though the equals() method fails, i changed == and used equals() instead but no changes happens, the problem remains.

  • 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-06-08T21:35:30+00:00Added an answer on June 8, 2026 at 9:35 pm

    Why does equals “never fail”?

    As per Tom’s comment:

    .. If you modify the object in the map but keep the key constant, then you’ll still be able to get the value using the same key instance. dog.equals(dog) will always be true with your code (unless there is concurrent modification)

    That is, the line:

    d1.name = "arthur"; 
    

    Is mutating the object already in the HashMap. Compare with (where t “prints” true or false):

    Dog d1 = new Dog("clover");
    // what "put" is effectively doing: there is *no* Copy/Clone
    Dog inMap = d1;
    t(inMap == d1);                 // true: same object, reference equality!
    d1.name = "arthur";
    t(inMap.name.equals("arthur")); // true: same object! "name" member was *mutated*
    t(d1.equals(inMap));            // true: same object!
    

    So the equals never fails because it is comparing the object with itself 🙂

    I missed it at first too: remember Java has Call By Object-Sharing semantics. That is, there is no implicit Copy/Clone/Duplicate for objects that are passed to methods.

    So then, how to get it to fail:

    Dog d1 = new Dog("clover");
    Dog d2 = new Dog("clover");
    t(d1 == d2);                   // false: different objects!
    m.put(d1, "Dog key");          // put in with D1 object
    System.out.println(m.get(d1)); // "Dog key"   -okay, equals
    System.out.println(m.get(d2)); // "Dog key"   -okay, equals
    d2.name = "arthur";            // *mutate* D2 object
    t(d1.equals(d2));              // false: no longer equal
    System.out.println(m.get(d1)); // "Dog key"   -okay, always equals, as per above
    System.out.println(m.get(d2)); // ""          -no good, no longer equals
    

    And how does the hashCode fit in?

    The hash code is used to determine the hash table bucket to put the key (and value pair) in. When performing a look-up (or set) the bucket is first looked up by hash code and then each key already mapped to the bucket is checked with equals. If there are no keys in the bucket then equals is never invoked.

    This explains why changing the name to a String of length 8 in the original post results in a failing look-up: a different bucket (say, one that is empty) is initially chosen and thus equals is never invoked upon existing keys which exist in other buckets. The same object key might be already there, but it’s never looked at!

    So then, how to get it to fail with different hash code:

    Dog d1 = new Dog("clover");
    m.put(d1, "Dog key");          // put in with D1 object, hashCode = 6
    System.out.println(m.get(d1)); // "Dog key" -okay, hashCode = 6, equals
    d1.name = "Magnolia";          // change value such that it changes hash code
    System.out.println(m.get(d1)); // ""        -fail, hashCode = 8, equals
    // ^-- attaching a debugger will show d1.equals is not called
    

    Thus, for a key to be found in a hash table (such as a HashMap) it must be such that:

    k.hashCode() == inMap.hashCode() && k.equals(inMap);
    

    There may be many hash codes that map to the same bucket. However the above is the only guarantee that a look-up will be successful.


    Of course, see the other replies for correct way to compare strings in general.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have below code which overrides equals() and hashcode() methods. public boolean equals(Object obj)
Why does StringBuffer/StringBuilder does not override the equals() , hashcode() methods from object? Please
public class Node { private Node nextNode; @Override public int hashCode() { //How to
I have a class Foo which overrides equals() and hashCode() properly. I would like
I'm using this class as my key to Hashmap with overriden hasCode() and equals()
Please clarify my doubt in Hashset. Consider the following code, class Person { String
The program was working with this implementation: class Instrument { public string ClassCode {
I have some object class A { private Long id; private String name; public
I tried to override equals and hashcode methods in a class. It is a
I have this class: private static class ClassA{ int id; String name; public ClassA(int

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.