AbstractList overrides the equals() method

Topic content

The content of the topic is very simple. It is to create ArrayList and Vector sets, add strings of the same content to them, and finally use the equals() method to compare whether they are equal.

Here we examine the knowledge points of "= =" and equals() methods.

At first, I thought the output was false, but after a little experiment, the result was true!

Why? Because I don't know that AbstractList, the common parent class of ArrayList and Vector, overrides the equals() method of the Object class.

The body of the rewriting method is as follows:

public boolean equals(Object o) {  
   // Here, we use = = to judge whether two sets refer to the same address or not, because it is = = compared
if (o == this) return true;
// Here, judge whether the comparison set is an instance of List. If not, return false directly
if (!(o instanceof List)) return false;
// Create iterator ListIterator
<E> e1 = listIterator(); ListIterator<?> e2 = ((List<?>) o).listIterator();
// If both have elements, compare whether they are equal
while (e1.hasNext() && e2.hasNext()) { E o1 = e1.next(); Object o2 = e2.next();
// The comparison rules are as follows:
     // 1. If one of the two elements is null, but the other is not null, false will be returned
//2. If one of the elements is not null, but the comparison between the two is false by using the equals() method, false will be returned
if (!(o1==null ? o2==null : o1.equals(o2))) return false; }
   // After the collection element variables are completed, and the loop body does not return the flag, false will be returned if any collection has elements
return !(e1.hasNext() || e2.hasNext()); }

Because the generic type of the collection in the topic is String, and String also overrides the equals() method, the content of the collection in the topic is the same, that is, the comparison result is true.

If the element contents are other and the equals() method is not overridden, the comparison result is false.

Such as:

public void test() {
    StringBuilder sb = new StringBuilder("demo");
    StringBuilder sb1 = new StringBuilder("demo");

    ArrayList<StringBuilder> arrayList = new ArrayList<StringBuilder>();
    arrayList.add(sb);

    Vector<StringBuilder> vector = new Vector<StringBuilder>();
    vector.add(sb1);

System.out.println(arrayList.equals(vector)); }

Supplement:

Many people don't know that the Integer class also overrides the equals() method

public boolean equals(Object obj) {
    if (obj instanceof Integer) {
//Obviously, it seems that = = comparison is used, but intValue() method is called to return int type, so = = is used to compare basic data type, which means whether the value is equal
return value == ((Integer)obj).intValue(); } return false; }

public int intValue() {
  return value;
}

Tags: Java

Posted on Mon, 02 Dec 2019 14:09:43 -0800 by leoo24