美文网首页
第 40 条:坚持使用Override注解

第 40 条:坚持使用Override注解

作者: 综合楼 | 来源:发表于2021-05-19 21:05 被阅读0次
    坚持使用Override注解.jpeg
    错误示例
    // Can you spot the bug?
    public class Bigram { 
      private final char first; 
      private final char second;
      public Bigram(char first, char second) { 
        this.first = first;
        this.second = second;
      }
      public boolean equals(Bigram b) {
        return b.first == first && b.second == second; 
      }
      public int hashCode() { 
        return 31 * first + second;
      }
      public static void main(String[] args) { 
        Set<Bigram> s = new HashSet<>(); 
        for (int i = 0; i < 10; i++)
          for (char ch = 'a'; ch <= 'z'; ch++) 
            s.add(new Bigram(ch, ch));
        System.out.println(s.size()); 
      }
    }
    
    
    正确示例
    public class Bigram { 
      private final char first; 
      private final char second;
      public Bigram(char first, char second) { 
        this.first = first;
        this.second = second;
      }
    
      @Override
      public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Bigram bigram = (Bigram) o;
        return first == bigram.first &&
                second == bigram.second;
      }
    
      @Override
      public int hashCode() {
        return Objects.hash(first, second);
      }
    
      public static void main(String[] args) { 
        Set<Bigram> s = new HashSet<>();
        for (int i = 0; i < 10; i++)
          for (char ch = 'a'; ch <= 'z'; ch++) 
            s.add(new Bigram(ch, ch));
        System.out.println(s.size()); 
      }
    }
    
    

    相关文章

      网友评论

          本文标题:第 40 条:坚持使用Override注解

          本文链接:https://www.haomeiwen.com/subject/bjzidltx.html