我可以让indexOf以不同的方式比较对象吗? [英] Can I make indexOf compare objects in a different way?

查看:143
本文介绍了我可以让indexOf以不同的方式比较对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想以与Object.equals方法不同的方式进行indexOf比较。我在考虑重写equals方法以改用我的IsEvalence方法,但我不确定如何做到这一点,如果可能的话。

我尝试了很多版本,但一直收到错误:

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

我也见过this answer他们谈论EqualityCompeller‘s,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
}

这篇关于我可以让indexOf以不同的方式比较对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆