Learning or doing things is easy to remember...
I 've been reading objective Java recently, but it has indeed improved a lot. I wrote down what I saw and thought of, and marked it...
1. Stick to the override annotation.
1 public class Bigram { 2 3 private final char first; 4 private final char second; 5 public Bigram(char first,char second) { 6 this.first = first; 7 this.second = second; 8 } 9 10 public boolean equals(Bigram bigram) {11 return bigram.first == first && bigram.second == second;12 }13 14 public int hashCode() {15 return 31*first + second;16 }17 18 public static void main(String[] args) {19 Set<Bigram> bigrams = new HashSet<Bigram>();20 for(int i=0;i<10;i++){21 for(char ch=‘a‘;ch<=‘z‘;ch++){22 bigrams.add(new Bigram(ch, ch));23 }24 }25 System.out.println(bigrams.size());26 }27 28 }
View code
This is an example.
260
The result is very interesting. Why is it 260 instead of 26?
BigramsThe set type used is hashset. Why didn't duplicate elements be removed?
1 /** 2 * Adds the specified element to this set if it is not already present. 3 * More formally, adds the specified element <tt>e</tt> to this set if 4 * this set contains no element <tt>e2</tt> such that 5 * <tt>(e==null ? e2==null : e.equals(e2))</tt>. 6 * If this set already contains the element, the call leaves the set 7 * unchanged and returns <tt>false</tt>. 8 * 9 * @param e element to be added to this set10 * @return <tt>true</tt> if this set did not already contain the specified11 * element12 */13 public boolean add(E e) {14 return map.put(e, PRESENT)==null;15 }
Let's take a look at the underlying description of the add method of hashset: 3 ~ The conditions for adding element e are described in Row 5: Element E2 (E = NULL; E2 = NULL; E. Equals (E2) does not exist in the set ))
If none of the elements are null, the code E. Equals (E2) is different from the expected result.
So let's take a look at the source code. Why does equals in the Code not play what we want?
1 public boolean equals(Object obj) {2 return (this == obj);3 }
This is the equals method in the object class. Take a closer look. The equals method was originally intended to be rewritten in the code, but the equals method was overloaded.
In this case, in this line of code (E. when equals (E2), The equals method of the object class is called, And the equals method of the object class is equivalent to the same object, that is, (E = e2)
Example: This line of code:Bigrams. Add (New bigram (ch, ch ));Each time you add a new bigram (ch, ch), each object is different. The number of times that a natural cycle occurs, and the number of objects that are added is the same.
If the annotation @ override is added, the modern ide will report an error:The method equals (bigram) of Type bigram must override or implement a supertype Method
Therefore, you should use the override annotation in each method declaration that you want to override the parent class declaration.