E
e.chaitanya
Hi all
We are trying to override the equals() and hashCode() methods for a
particular class. Given below is a piece of code we have tested:
import java.util.*;
public class SetCompare {
private int val;
private String data = "TestString";
public SetCompare(int val)
{
this.val=val;
}
public int hashCode()
{
System.out.println("Hashed! :"+val);
int hash = 7;
hash = 31 * hash + val;
hash = 31 * hash + (null == data ? 0 : data.hashCode());
System.out.println("Hashed value :"+hash);
return hash;
}
public boolean equals(Object obj)
{
System.out.println("\n *************");
if(this == obj)
return true;
if((obj == null) || (obj.getClass() != this.getClass()))
return false;
// object must be Test at this point
SetCompare test = (SetCompare)obj;
return val == test.val &&
(data == test.data || (data != null && data.equals(test.data)));
/*if(!(a1 instanceof SetCompare))
return false;
if(this.val==((SetCompare)a1).val)
return true;
else
return false;*/
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Set newSet = new HashSet();
SetCompare obj1 = new SetCompare(1);
SetCompare obj2 = new SetCompare(2);
newSet.add(obj1);
newSet.add(obj2);
if (newSet.contains(obj1))
System.out.println("\n Test");
}
}
However, this piece of code does not call the equals() method when the
"newSet.contains(obj1)" or "newSet.add(obj2)" is called. Could any of
you suggest a fix for this and also help us identify the problem with
it.
Thank You
---
We are trying to override the equals() and hashCode() methods for a
particular class. Given below is a piece of code we have tested:
import java.util.*;
public class SetCompare {
private int val;
private String data = "TestString";
public SetCompare(int val)
{
this.val=val;
}
public int hashCode()
{
System.out.println("Hashed! :"+val);
int hash = 7;
hash = 31 * hash + val;
hash = 31 * hash + (null == data ? 0 : data.hashCode());
System.out.println("Hashed value :"+hash);
return hash;
}
public boolean equals(Object obj)
{
System.out.println("\n *************");
if(this == obj)
return true;
if((obj == null) || (obj.getClass() != this.getClass()))
return false;
// object must be Test at this point
SetCompare test = (SetCompare)obj;
return val == test.val &&
(data == test.data || (data != null && data.equals(test.data)));
/*if(!(a1 instanceof SetCompare))
return false;
if(this.val==((SetCompare)a1).val)
return true;
else
return false;*/
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Set newSet = new HashSet();
SetCompare obj1 = new SetCompare(1);
SetCompare obj2 = new SetCompare(2);
newSet.add(obj1);
newSet.add(obj2);
if (newSet.contains(obj1))
System.out.println("\n Test");
}
}
However, this piece of code does not call the equals() method when the
"newSet.contains(obj1)" or "newSet.add(obj2)" is called. Could any of
you suggest a fix for this and also help us identify the problem with
it.
Thank You
---