Ref: Effective Java by Joshua Bloch
Can you spot the bug?:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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<Bigram>(); | |
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()); | |
} | |
} |
The program tries to utilize equals method of Object by intention of overriding equals method, but it can not, since to override Object.equals, you must define an equals method whose parameter is of type Object.
Luckily, the compiler can help you find this error, but only if you help the compiler by telling it that you intend to override Object.equals. To do this, annotate Bigram.equals with @Override as shown below
@Override public boolean equals(Bigram b) {
return b.first == first && b.second == second;
}Therefore, you should use the Override annotation on every method decleration that you believe to override a superclass decleration.
No comments:
Post a Comment