ArrayList not using the overridden equals

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

    in the other way, your equal method gets called if you change your code as follows. hope this clears the concept.

    package com.test;
    
    import java.util.ArrayList;    
    import java.util.List;
    
    public class TestClass  {
        private static class InnerClass{    
            private final String testKey;
            //data and such
    
            InnerClass(String testKey, int dataStuff) {
                this.testKey =testKey;
                //etc
            }
    
            @Override
            public boolean equals (Object in1) {
                System.out.println("reached here");
                if(in1 == null) {
                    return false;
                }else if( in1 instanceof InnerClass) {
                    return ((InnerClass) this).testKey == null ? false : ((InnerClass) this).testKey.equals(((InnerClass) in1).testKey);
                }else {
                    return false;
                }       
            }       
        }
    
        public static void main(String[] args) {    
            ArrayList objectList = new ArrayList();
            InnerClass in1 = new InnerClass("UNIQUE ID1", 42);
            InnerClass in2 = new InnerClass("UNIQUE ID1", 42);
    
            //add some entries
            objectList.add(in1);
            System.out.println( objectList.contains(in2)); 
        }    
    }
    

提交回复
热议问题