use*_*269 11 java collections hashset
假设我有两个不同的哈希集,如下所示,我如何检查两个哈希集包含相同的元素,这两个哈希集是相等的,独立于集合中元素的顺序,请指教.. !!
Set set1=new HashSet();
set.add(new Emp("Ram","Trainer",34000));
set.add(new Emp("LalRam","Trainer",34000));
Run Code Online (Sandbox Code Playgroud)
另一个是......
Set set2=new HashSet();
set.add(new Emp("LalRam","Trainer",34000));
set.add(new Emp("Ram","Trainer",34000));
Run Code Online (Sandbox Code Playgroud)
员工pojo是......
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;
}*/
}
Run Code Online (Sandbox Code Playgroud)
Pet*_*lák 89
引自AbstractSet.equals(Object)的 javadoc:
如果给定对象也是一个集合,则返回true,两个集合具有相同的大小,并且给定集合的每个成员都包含在此集合中.这可确保equals方法在Set接口的不同实现中正常工作.
所以简单地打电话就足够了set1.equals(set2).true当且仅当集合包含相同的元素时(假设您已正确定义equals并且hashCode在集合中的对象上),它将返回.
Aar*_*als 11
使用以下表达式.
set1.containsAll(set2) && set2.containsAll(set1)
Run Code Online (Sandbox Code Playgroud)
假设你已经定义了equals和hashcode,这是一种方法.对大型会员来说效率不高.
更新:我不知道containsAll,这节省了很多麻烦,基本上做了算法
int s1 = set1.size();
int s2 = set2.size();
if (s1 !=s2) return false;
return set1.containsAll(set2);
Run Code Online (Sandbox Code Playgroud)
小智 -5
除非您出于某种原因需要实现自己的方法,否则只需使用
h1.equals(h2). 下面描述了一种可能的实现方式。
例子:
public boolean isIdenticalHashSet <A> (HashSet h1, HashSet h2) {
if ( h1.size() != h2.size() ) {
return false;
}
HashSet<A> clone = new HashSet<A>(h2); // just use h2 if you don't need to save the original h2
Iterator it = h1.iterator();
while (it.hasNext() ){
A = it.next();
if (clone.contains(A)){ // replace clone with h2 if not concerned with saving data from h2
clone.remove(A);
} else {
return false;
}
}
return true; // will only return true if sets are equal
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44052 次 |
| 最近记录: |