File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hashcode

 
sangeetha balasubramaniam
Greenhorn
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not in scope of SCJP. Moving to Java in General (Intermediate)
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Norm Radder
Ranch Hand
Posts: 707
3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3061
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic