我可以让indexOf以不同的方式比较对象吗?

Aeq*_*tas 5 java equality equals indexof

我想使用indexOf,但 中的对象List不会是相等的对象,但它们的值相等(即它们相等但不相等)。

我想以indexOf与方法不同的方式进行比较Object.equals。我正在考虑重写 equals 方法以使用 isEquivalent 方法,但我不确定如何执行此操作(如果可能的话)。

我已经尝试了很多变体,但不断收到错误:

List<CustomType> items{
        @Override
        public boolean equals(Object o)
        {
             return false;
        }
    }
    = //stuff to populate it
Run Code Online (Sandbox Code Playgroud)

我也看到了这个答案,他们谈论 EqualityComparer's java 中是否有类似的东西?

或者还有其他方法可以实现这一点吗?

cri*_*007 4

这是我的破解方法。我使用ArrayListList 是因为 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
Run Code Online (Sandbox Code Playgroud)

或者

我之前在评论中想说的是,如果您重写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
}
Run Code Online (Sandbox Code Playgroud)