ArrayList not using the overridden equals

后端 未结 11 1396
误落风尘
误落风尘 2021-02-08 14:13

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

11条回答
  •  离开以前
    2021-02-08 15:09

    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;
    }
    

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

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

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

提交回复
热议问题