This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashcode

 
PUNNU GULATI
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic