wood burning stoves 2.0*
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
Author

Hashcode

sangeetha balasubramaniam
Greenhorn

Joined: May 16, 2005
Posts: 23
Hi,

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);
tempProj.append(pid.replaceAll("/","").replaceAll("T","3").replaceAll("P","2").replaceAll("C","1").replaceAll("D","4"));

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
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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: 685
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.

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

Java API Documentation
The Java Tutorial
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Hashcode
 
Similar Threads
overriding hashcode and equals method internal work flow
HashMap keys
How to choose correct hashCode method
About the advantages of overriding equals()
equals and ==