ArrayList不使用重写的equals [英] ArrayList not using the overridden equals

查看:417
本文介绍了ArrayList不使用重写的equals的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了使ArrayList正确使用overriden equals的问题。问题是我试图使用equals仅测试单个键字段,并使用ArrayList.contains()来测试具有正确字段的对象的存在。下面是一个示例

I'm having a problem with getting an ArrayList to correctly use an overriden equals. the problem is that I'm trying to use the equals to only test for a single key field, and using ArrayList.contains() to test for the existence of an object with the correct field. Here is an example

public class TestClass  {
    private static class InnerClass{    
    private final String testKey;
    //data and such

    InnerClass(String testKey, int dataStuff) {
        this.testKey =testKey;
        //etc
    }
    @Override
    public boolean equals (Object in) {
        System.out.println("reached here");
        if(in == null) {
        return false;
        }else if( in instanceof String) {
        String inString = (String) in;
        return testKey == null ? false : testKey.equals(inString);
        }else {
        return false;
        }       
    }       
    }

    public static void main(String[] args) {    
    ArrayList<InnerClass> objectList = new ArrayList<InnerClass>();
    //add some entries
    objectList.add(new InnerClass("UNIQUE ID1", 42));
    System.out.println( objectList.contains("UNIQUE ID1")); 
    }    
}

令我担心的是,我不仅会得到假的在输出上,但我也没有得到到达这里输出。

What worries me is that not only am I getting false on the output, but I'm also not getting the "reached here" output.

有没有人有任何想法为什么这个覆盖被完全忽略?是否有一些微妙的覆盖和内部类我不知道?

Does anyone have any ideas why this override is being completely ignored? Is there some subtlety with overrides and inner classes I don't know of?

编辑:
网站出现问题所以我似乎无法标记答案。
感谢您的快速回复:是的,我的疏忽是它是字符串.equals thta被称为,而不是我自定义的。我想这是现​​在的老式支票

Having problems with the site so I cant seem to mark the answered. Thanks for the quick response: yes an oversight on my part that it is the String .equals thta is called, not my custom one. I guess it's old fashioned checks for now

推荐答案

如果检查 ArrayList的来源,你会看到它调用其他对象的等于。在你的情况下,它将调用等于的字符串UNIQUE ID1,它将检查其他对象是否为字符串并且只返回 false

If you check sources of ArrayList, you will see that it calls equals of other object. In your case it will call equals of String "UNIQUE ID1" which will check that other object is not of type String and just returns false:

public boolean contains(Object o) {
    return indexOf(o) >= 0;
}

public int indexOf(Object o) {
    ...     
    for (int i = 0; i < size; i++)
    if (o.equals(elementData[i]))
        return i;
    ...
    return -1;
}

对于您的案例来说,包含 InnerClass 只包含 id

For your case call contains with InnerClass that only contains id:

objectList.contains(new InnerClass("UNIQUE ID1"))

不要忘记为 InnerClass 实施等于,其中 id only。

Don't forget to implement equals for InnerClass which compares id only.

这篇关于ArrayList不使用重写的equals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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