ArrayList not using the overridden equals

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

    Generally, you need to also override hashCode() but this is not the main problem here. You are having an asymmetric equals(..) method. The docs make it clear that it should be symmetric:

    It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

    And what you observe is an unexpected behaviour due to broken contract.

    Create an utility method that iterates all items and verifies with equals(..) on the string:

    public static boolean containsString(List items, String str) {
        for (InnerClass item : items) {
            if (item.getTestKey().equals(str)) {
               return true;
            }
        }
        return false;
    } 
    

    You can do a similar thing with guava's Iterables.any(..) method:

    final String str = "Foo";
    boolean contains = Iterables.any(items, new Predicate() {
       @Override
       public boolean apply(InnerClass input){ 
           return input.getTestKey().equals(str);
       }
    }
    

提交回复
热议问题