ArrayList not using the overridden equals

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

    Your equals implementation is wrong. Your in parameter should not be a String. It should be an InnerClass.

    public boolean equals(Object o) {
      if (this == o) return true;
      if (!(o instanceof InnerClass) return false;
      InnerClass that = (InnerClass)o;
      // check for null keys if you need to
      return this.testKey.equals(that.testKey);
    }
    

    (Note that instanceof null returns false, so you don't need to check for null first).

    You would then test for existence of an equivalent object in your list using:

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

    But if you really want to check for InnerClass by String key, why not use Map instead?

提交回复
热议问题