Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL
Help

Chapter 6. Enums and Annotations > Item 36: Consistently use the Override annot... - Pg. 176

176 CHAPTER 6 ENUMS AND ANNOTATIONS Item 36: Consistently use the Override annotation When annotations were added to the language in release 1.5, several annotation types were added to the libraries [JLS, 9.6.1]. For the typical programmer, the most important of these is Override . This annotation can be used only on method declarations, and it indicates that the annotated method declaration overrides a declaration in a supertype. If you consistently use this annotation, it will protect you from a large class of nefarious bugs. Consider this program, in which the class Bigram represents a bigram, or ordered pair of letters: // 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 main program repeatedly adds twenty-six bigrams, each consisting of two identical lowercase letters, to a set. Then it prints the size of the set. You might expect the program to print 26 , as sets cannot contain duplicates. If you try run- ning the program, you'll find that it prints not 26 but 260 . What is wrong with it? Clearly, the author of the Bigram class intended to override the equals method (Item 8) and even remembered to override hashCode in tandem (Item 9). Unfortunately, our hapless programmer failed to override equals , overloading it instead (Item 41). To override Object.equals , you must define an equals method whose parameter is of type Object , but the parameter of Bigram 's equals