File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Hashcode Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Hashcode" Watch "Hashcode" New topic


sangeetha balasubramaniam

Joined: May 16, 2005
Posts: 23

Can a hashcode overridden from Object, can return other than int.

Because i can an object which has teh value that sis greater then the int can hold.No way of reducing the value of my object, because i have to check against the same object.I even tried dividing the value by some int to make it smaller value so taht it can fit in int, this case recults me in same hashcode for different objects.

String pid = "P1/000032";
String cid = "20"
public int hashCode(){
StringBuffer tempProj = new StringBuffer(50);

long lValue = Long.parseLong(tempProj.toString())/(Integer.parseInt(cid)*99);
return (int)lValue;

Above code returns 10606 for pid = "P1/000032" and also "P1/000034".Help please.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Not in scope of SCJP. Moving to Java in General (Intermediate)

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

It's perfectly OK if different objects have the same hashCode. equal() objects must have the same hashCode, but unequal objects just should have different ones. In the general case, there's no way to guarantee uniqueness, and that's just fine.

[Jess in Action][AskingGoodQuestions]
Norm Radder
Ranch Hand

Joined: Aug 10, 2005
Posts: 694
If an object's hashcode is mainly used as in index into Hashtable's buckets, I doubt if a Hashtable could have more than 2+ billion buckets.
hashcode is a way of mapping a number (everything on a computer is a number) evenly into a smaller space.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
If the result of your calculation is too big, you can use the modulus operator (%) to limit it to a particular range. As noted above, this means that to unequal objects will probably have equal hashcodes, but this is okay and typically unavoidable.

[ September 11, 2005: Message edited by: Layne Lund ]

Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: Hashcode
It's not a secret anymore!