import java.util.*;
class hashcodeoverriding
{
String s;
hashcodeoverriding(String p)
{
s=p;
}
public boolean equals(Object o)
{
if((o instanceof hashcodeoverriding) && (this .s==((hashcodeoverriding)o).s))
return true;
else return false;
}
public int hashcode()
{
//return (s.length());
return 5;
}
//public String toString()
//{
//return s;
//}
public static void main(String...args)
{
HashSet x=new HashSet();
x.add(new hashcodeoverriding("Ram"));
x.add(new hashcodeoverriding("Prad"));
x.add(new hashcodeoverriding("Prad"));
System.out.println(x.size());
}
}
SCJP 5.0(75%), SCWCD 5.0(88%)
SCJP 5.0(75%), SCWCD 5.0(88%)
]A common source of bugs is the failure to override the hashCode method. You must override hashCode in every class that overrides equals. Failure to do so will result in a violation of the general contract for Object.hashCode, which will prevent your class from functioning properly in conjunction with all hash-based collections,including HashMap, HashSet, and Hashtable.[/B
[B]So to be truly safe, your rule of thumb should
be, if you override equals(), override hashCode() as well. Kathy & Bates
import java.util.*;
class SetTest
{ int i;
SetTest(int x)
{
i=x;
}
public static void main(String...args)
{
Set s=new HashSet();
s.add("a");
s.add(new Integer(42));
s.add("b");
s.add("a");
s.add(new Object());
//s.add(new SetTest(50));
//s.add(new SetTest(50));
for(Object o:s)
System.out.println(o +"");
}
}
SCJP 5.0(75%), SCWCD 5.0(88%)
SCJP 5.0(75%), SCWCD 5.0(88%)
Please also tell me Is it(hashCode()) implicitely called and if yes then who called it?
Which other classes other than Integer and String ,are override the hashCode() method.
SCJP 5.0(75%), SCWCD 5.0(88%)
Which other classes other than Integer and String ,are override the hashCode() method.
Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |