Java Set collection - override equals method

前端 未结 5 728
孤城傲影
孤城傲影 2020-12-14 17:08

Is there any way to override the the equals method used by a Set datatype? I wrote a custom equals method for a class called Fee

5条回答
  •  Happy的楠姐
    2020-12-14 17:44

    You can and should use a Set to hold an object type with an overridden equals method, but you may need to override hashCode() too. Equal objects must have equal hash codes.

    For example:

    public Fee{
    
        public String fi;
    
        public String fo;
    
        public int hashCode(){
    
            return fi.hashCode() ^ fo.hashCode();
        }
    
        public boolean equals(Object obj){
    
            return fi.equals(obj.fi) && fo.equals(obj.fo);
        }
    }
    

    (With null checks as necessary, of course.)

    Sets often use hashCode() to optimize performance, and will misbehave if your hashCode method is broken. For example, HashSet uses an internal HashMap.

    If you check the source code of HashMap, you'll see it depends on both the hashCode() and the equals() methods of the elements to determine equality:

    if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
    

    If the hash is not generated correctly, your equals method may never get called.

    To make your set faster, you should generate distinct hash codes for objects that are not equal, wherever possible.

提交回复
热议问题