Earlier I had posted a ques regarding hashCode n' equals..
But the code was incorrect...
So here is the correct code n the question follows...
[/QUOTE]
/* Testing some ambiguous equals n' hashcode concepts
@Author Nitish Upreti
*/
class Car
{
private String model;
private char type;
private int carno; //The core attribute for deciding if two car objects are equal
public Car()
{
model="Merc";
type='S';
carno=95361;
}
public Car(int no)
{
model="Merc";
type='M';
carno=95361;
}
public boolean equals(Object o)
{
Car c=new Car();
if(o instanceof Car)
c=(Car)o;
/*
System.out.println("c hashCode()--- "+c.hashCode());
System.out.println("Current Object's hashCode()--- "+this.hashCode());
*/
if(c.carno==this.carno)
return true;
else
return false;
}
public int hashcode()
{
return type;
}
public static void main(String args[])
{
Car c=new Car();
Car c2=new Car(13458);
System.out.println("In main() c hashCode()--- "+c.hashCode());
System.out.println("In main() c hashCode()--- "+c2.hashCode());
if(c.equals(c2))
System.out.println("Same Car---Number is same dude
");
else
System.out.println("Different Cars----Nameplate check kar
");
}
}
[/QUOTE]
The hashCodes() are reported to b unequal...still the objects are equals!!
Why is it so??
I read in books that for two objects to b equal they must be logically equal n' also have the same hashcode