问题陈述
我有两个要比较的相同类型对象的集合。在这种情况下,我想根据不考虑的属性来比较它们equals()
对于对象。在我的示例中,我使用排名的名称集合,例如:
public class Name {
private String name;
private int weightedRank;
//getters & setters
@Override
public boolean equals(Object obj) {
return this.name.equals(obj.name); //Naive implementation just to show
//equals is based on the name field.
}
}
我想比较这两个集合来断言,对于位置i
在每个集合中,weightedRank
该位置的每个名称的值相同。我做了一些谷歌搜索,但没有在 Commons Collections 或任何其他 API 中找到合适的方法,所以我想出了以下方法:
public <T> boolean comparatorEquals(Collection<T> col1, Collection<T> col2,
Comparator<T> c)
{
if (col1 == null)
return col2 == null;
if (col2 == null)
return false;
if (col1.size() != col2.size())
return false;
Iterator<T> i1 = col1.iterator(), i2 = col2.iterator();
while(i1.hasNext() && i2.hasNext()) {
if (c.compare(i1.next(), i2.next()) != 0) {
return false;
}
}
return true;
}
Question
还有其他方法可以做到这一点吗?我是否错过了 Commons Collections 中的一个明显方法?
Related
我也发现了这个问题 https://stackoverflow.com/questions/11758220/a-mechanism-for-having-different-equals-physical-equals-and-logical-equals-on在 SO 上,这很相似,但在这种情况下我认为最重要的是equals()
更有意义一点。
Edit
与此非常相似的东西将进入发布版本Apache 共享集合 http://commons.apache.org/proper/commons-collections/在不久的将来(在撰写本文时)。看https://issues.apache.org/jira/browse/COLLECTIONS-446 https://issues.apache.org/jira/browse/COLLECTIONS-446.