Let say I have two different hashsets as shown below how can I check that two Hashset contain the same elements and these two hashsets are equal, independent of the order of elements in collection, please advise..!!
Set set1=new HashSet();
set.add(new Emp("Ram","Trainer",34000));
set.add(new Emp("LalRam","Trainer",34000));
and the other one is ..
Set set2=new HashSet();
set.add(new Emp("LalRam","Trainer",34000));
set.add(new Emp("Ram","Trainer",34000));
The employee pojo is ...
class Emp //implements Comparable
{
String name,job;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
int salary;
public Emp(String n,String j,int sal)
{
name=n;
job=j;
salary=sal;
}
public void display()
{
System.out.println(name+"\t"+job+"\t"+salary);
}
public boolean equals(Object o)
{
Emp p=(Emp)o;
return this.name.equals(p.name)&&this.job.equals(p.job) &&this.salary==p.salary;
}
public int hashCode()
{
return name.hashCode()+job.hashCode()+salary;
}
/* public int compareTo(Object o)
{
Emp e=(Emp)o;
return this.name.compareTo(e.name);
//return this.job.compareTo(e.job);
// return this.salary-e.salary;
}*/
}
Emp
has proper overrides forequals()
andhashCode()
(which it probably does, given its presence in a hash table) you could compare counts on the sets, and then try to add every element of one set to the other. If theadd()
method ever returnstrue
, then there's a difference.Set
. Sets have no implicit order. Second, you haven't specified what you mean by "equals". For collections, it could be "the two collections contain the same set of references to actual elements", or "All elements from collection A compare equal (viaequals()
) to their corresponding element in collection B". You seem to want the latter definition, which is trickier to implement.