Member-only story
Effective Java! Consistently Use the Override Annotation
In our previous chapter we discussed creating annotations which was a lot of fun but not something that a lot of developers will find themselves doing on a day-to-day basis. Today we discuss something that you will interact with much more often. That is the @Override
annotation. This annotation is quite simple but will help avoid some bugs and push detection of some of our defects to compile-time versus later in the process. To illustrate the point let us consider the following example:
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 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());
}
}
This code loops through the lowercase alphabet and adds two of the same character as Bigram
to a set. It repeats this operation ten times. Seeing as it's doing the same thing over and over and putting the results in the set and duplicates can't be put into a set you would likely expect the size to be 26 but it actually ends up with 260…