ArrayList not using the overridden equals

后端 未结 11 1402
误落风尘
误落风尘 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 14:50

    As many posts have said, the problem is that list.indexOf(obj) function calls "equals" of the obj, not the items on the list.

    I had the same problem and "contains()" didn't satisfy me, as I need to know where is the element!. My aproach is to create an empty element with just the parameter to compare, and then call indexOf.

    Implement a function like this,

    public static InnerClass empty(String testKey) {
        InnerClass in = new InnerClass();
        in.testKey =testKey;
        return in;
    }
    

    And then, call indexOf like this:

    ind position = list.indexOf(InnerClass.empty(key));
    

提交回复
热议问题