ArrayList not using the overridden equals

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

    There are a few issues with your code. My suggestion would be to avoid overriding the equals entirely if you are not familiar with it and extend it into a new implementation like so...

    class MyCustomArrayList extends ArrayList{
    
        public boolean containsString(String value){
            for(InnerClass item : this){
                if (item.getString().equals(value){
                    return true;
                }
            }
            return false;
        }
    
    }
    

    Then you can do something like

    List myList = new MyCustomArrayList()
    myList.containsString("some string");
    

    I suggest this because if you override the equals should also override the hashCode and it seems you are lacking a little knowledge in this area - so i would just avoid it.

    Also, the contains method calls the equals method which is why you are seeing the "reached here". Again if you don't understand the call flow i would just avoid it.

提交回复
热议问题