ArrayList not using the overridden equals

后端 未结 11 1405
误落风尘
误落风尘 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:04

    You're invoking contains with an argument that's a String and not an InnerClass:

    System.out.println( objectList.contains("UNIQUE ID1"))
    

    In my JDK:

    public class ArrayList {
    
        public boolean contains(Object o) {
        return indexOf(o) >= 0;
        }
    
        public int indexOf(Object o) {
        if (o == null) {
            // omitted for brevity - aix
        } else {
            for (int i = 0; i < size; i++)
            if (o.equals(elementData[i])) // <<<<<<<<<<<<<<<<<<<<<<
                return i;
        }
        return -1;
        }
    }
    

    Note how indexOf calls o.equals(). In your case, o is a String, so your objectList.contains will be using String.equals and not InnerClass.equals.

提交回复
热议问题