我想使用,indexOf
但是中的对象List
将不是相等的对象,但是它们将具有相等的值(即,它们是等效的但不相等)。
我想以indexOf
不同于该Object.equals
方法的方式进行比较。我当时正在考虑改用equals方法来使用我的isEquivalent方法,但不确定(即使有可能)如何执行此操作。
我已经尝试了许多变体,但是不断出错:
List<CustomType> items{
@Override
public boolean equals(Object o)
{
return false;
}
}
= //stuff to populate it
我在他们谈论EqualityComparer的地方也看到了这个答案,在Java中是否有类似的东西?
还是有其他方法可以做到这一点?
这是我的努力。我使用过,ArrayList
因为List是一个接口,您将需要重写所有方法。
List<CustomType> customList = new ArrayList<CustomType>() {
@Override
public int indexOf(Object o) {
if (o instanceof CustomType) {
for (int i = 0; i < this.size(); i++) {
CustomType c = (CustomType) o;
if (c.isEquivalent(this.get(i))) {
return i;
}
}
}
return -1;
}
};
// use indexOf like normal, but beware of side-effects as mentioned in the comments
我在前面的评论中试图说的是,如果您覆盖List.equals
,则意味着您正在将List
对象与另一个对象而不是列表中的对象进行比较。要完成您要问的事情,您需要这样做。
class CustomType {
public boolean isEquivalent(CustomType ct) {
return true; // TODO: Implement this
}
@Override
public boolean equals(Object obj) {
// TODO: Implement this
if (obj instanceof CustomType) {
return this.isEquivalent((CustomType) obj);
}
return false;
}
@Override
public int hashCode() {
return super.hashCode(); // TODO: Implement this
}
}
public static void main(String args[]) {
List<CustomType> lst = new ArrayList<CustomType>();
// use indexOf like normal
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句