-2

why hashcode are same of string object ???

I'm trying to understand how string pool works.I have gone through many sites and finally i'm more confused now. Let me put down my doubts here. Someone help me in understanding them.

class cov {

    public static void main(String[] args) {
        String s = "abc"; //Object on string pool  
        System.out.println(s.hashCode());
        String str = new String("abc"); //This statement does two things  
        System.out.println(str.hashCode());


    }
}
1
  • The question that this has been marked as a duplicate of is a completely different question! Did anyone bother to check before closing this? Voting to reopen. Commented Feb 23, 2014 at 9:07

3 Answers 3

3

A String's hashCode() method is calculated based on the chars it contains. If two String objects contain the same chars with the same case and in the same order, then they will have the same hashCode().

Sign up to request clarification or add additional context in comments.

14 Comments

@user2723924 all objects in java are on the heap.
@user2723924: your point being?
@user2723924 I'm not sure what part of all objects in java are on the heap was unclear, or what it is you're asking.
I swear I'm going to write a blog post titled "there's nothing special about strings in java".
@HovercraftFullOfEels I think we're violently agreeing with each other, but my point is that if you treat a String like any other object in java, there's no surprises. The confusion seems to come from people thinking it's special because of the things you mention.
|
3

The String class has a hashCode method that calculates the hash code from its content, not from its memory location. So if two strings are identical (but not necessarily equal), they will have the same hash code.

If this were not the case, a structure such as HashSet<String> would be unusable - every new String would turn out not to be in the set, even when a String with the same characters had already been added.

Comments

1

Below is the source code which is used for generating hashCode

public int hashCode() {
int h = hash;
if (h == 0) {
    int off = offset;
    char val[] = value;
    int len = count;

        for (int i = 0; i < len; i++) {
            h = 31*h + val[off++];
        }
        hash = h;
    }
    return h;
}

And as described in other answers hashCode is generated from the contents of the String not the place where it is residing. e.g heap stack or constant pool

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.