aspose file tools*
The moose likes Beginning Java 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 » Beginning Java
Bookmark "hashcode" Watch "hashcode" New topic
Author

hashcode

PUNNU GULATI
Greenhorn

Joined: Feb 19, 2001
Posts: 6
Hello Everyone.
How are you
WE HAVE A LITTLE PROBLEM IN WRAPPER CLASSES.
public class wr
{
public static void main(String s[])
{
String str=new String("hello");
int obj=str.hashCode();
System.out.println("Hash code OF STRING is:"+obj);//1.HASH CODE IS 99162322

Double b2=Double.valueOf("3.0");
Double b3=new Double("4.0");
Integer b4=new Integer("77");

int obj2=b2.hashCode();
int obj3=b3.hashCode();
int obj4=b4.hashCode();

System.out.println(obj2);//2.HASH CODE IS 1074....
System.out.println(obj3);//3.HASH CODE IS 10745.....
System.out.println(obj4);//4.HASH CODE IS 77
}
}
QUESTION
1-
WHY IN THE CASE OF INTEGER HAS THE SAME HASH CODE AS ITS VALUE?

THANK'S

Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
Each class overrides the hashCode method differently. They just have to return an int value that can be sorted and used by Classes such as HashTable. Remember- anyone can invent a hashcode method. Sooner or later you will probably invent one for some personal class of your own.
This is the method from inside the Integer class. It just returns the integer itself. This is adequate because it provides a sortable int.

This is the method from inside the Double class. It has to get rid of any decimals so that the vale returned will fit into an int.


This is the method from String. It has to invent some conversion algorithm to assign int values to each char in the String.


"JavaRanch, where the deer and the Certified play" - David O'Meara
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: hashcode