Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Some questions about hashCode method

Status
Not open for further replies.

alebu

Programmer
Sep 7, 2002
46
Do I understand correctly that 2 equals objects MUST return the same hashCode() value BUT if 2 objects has the same hashCode it is DOES'NT mean that they are equals?
 
Not exactly, and yes.

2 Objects which are equal (in your definition or interest in being them equal) should return the same hashCode, but they don't must.
When you override equals you should override hashCode too, and vice versa.

And yes - two Objects might return the same hashcode, but be completely different.

seeking a job as java-programmer in Berlin:
 
ps: If you override hashcode and equals, you should of course implement it in a way, that only two objects, which you consider to be equal, produce the same hashcode.

But you shouldn't think of very different Objects when implementing hashcode.
Example:
Code:
class Usbstick
{
	private int price;
	public int hashCode ()	{ return price; }
	public Usbstick (int p)	{ price = p; }
}

class User
{
	private int id;
	private int age;
	// not the best implementation:
	public int hashCode ()	{ return 100*age + id;	}
	public User (int i, int a) { age = a; id = i;	}
}

public UserHash (String param)
{
	User u1 = new User (100, 0);
	User u2 = new User (0, 1);
	Usbstick u3 = new Usbstick (100);
	System.out.println (u1.hashCode () + " " + u2.hashCode () + " " + u3.hashCode ());
}

seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top