• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

hashcode

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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

 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic