Example of ==, equals and hashcode in java?

Does compare real equality of OBJECTS (I mean - both references point to the same object), not their content, whereas . Equal compares content ( at least for String ). String a = new String("aa"); String be = new String("aa"); a and be are pointing to different objects.

Does compare real equality of OBJECTS (I mean - both references point to the same object), not their content, whereas . Equal compares content ( at least for String ). String a = new String("aa"); String be = new String("aa"); a and be are pointing to different objects.

Notice also that if objects are equal then their hashchodes must be the same, but if hashcodes are the same, it doesn't mean that objects are equal.

The equals contract says that if o1. Equals(o2), then o1.hashCode() == o2.hashCode(). It doesn't specify anything about the hash codes of unequal objects.

You could have a method like public int hashCode() { return 42; } and it'd fulfill the contract. It's just expected that the hash code be related to the value of the object, in order to make hash tables work more efficiently. Now, as for why your == doesn't work, two objects will always be compared by reference.

That is, if o1 == o2, then o1 and o2 are the exact same object. That's rarely what you want; you usually want to see if o1. Equals(o2) instead.

1 for actually answering the question that was asked – Sean Owen Apr 28 '10 at 18:19.

When you use ==, you are comparing if two variables hold reference to the same Object. In other words s1 == s2 is like asking: are the s1 and s2 variables referring to the same String object? And that's not true, even when both String objects have the same "abc" value.

When you use equals(), you are comparing the value of both objects. Both objects may not be the same, but their value (in this case "abc") is the same, so it returns true. How do you define whether an object is equal to another?

That's up to you. In this case the String object already defines this for you, but for example if you define a Person object, how do you know if a person P1 is equal to P2? You do that by overriding equals() and hashCode().

Tells you whether the two variable references point at the same object in memory, nothing more. Equals() and hashCode() both look at the contents of the object and each uses its own algorithm for calculation.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions