Java Set collection - override equals method

前端 未结 5 724
孤城傲影
孤城傲影 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条回答
  •  [愿得一人]
    2020-12-14 17:39

    As Jeff Foster said:

    The Set.equals() method is only used to compare two sets for equality.

    You can use a Set to get rid of the duplicate entries, but beware: HashSet doesn't use the equals() methods of its containing objects to determine equality.

    A HashSet carries an internal HashMap with entries and uses equals() as well as the equals method of the HashCode to determine equality.

    One way to solve the issue is to override hashCode() in the Class that you put in the Set, so that it represents your equals() criteria

    For Example:

    class Fee {
          String name;
    
      public boolean equals(Object o) {
          return (o instanceof Fee) && ((Fee)o.getName()).equals(this.getName());
      }
    
      public int hashCode() {
          return name.hashCode();
      }
    
    }
    

提交回复
热议问题