ArrayList.containsAll does not use my regular equality function

The following code is a JUnit test function that does not execute when executed.

List<KGramPostingsEntry> a = new ArrayList<KGramPostingsEntry>();
List<KGramPostingsEntry> b = new ArrayList<KGramPostingsEntry>();
KGramPostingsEntry entry = new KGramPostingsEntry(1);
a.add(entry);

entry = new KGramPostingsEntry(1);
b.add(entry);

assertTrue(a.containsAll(b));

It uses a class KGramPostingsEntry:

package ir;

public class KGramPostingsEntry {
    int tokenID;

    public KGramPostingsEntry(int tokenID) {
        this.tokenID = tokenID;
    }

    public KGramPostingsEntry(KGramPostingsEntry other) {
        this.tokenID = other.tokenID;
    }

    public String toString() {
        return tokenID + "";
    }
    public boolean equals(KGramPostingsEntry other) {
        if(other.tokenID == this.tokenID) {
            return true;
        }
        return false;
    }
}

As you can see, the class has a function equals()that compares tokenIDdifferent objects KGramPostingsEntry. It seems to me that this function is not used when called containsAll()in the test. Further experiments seem to confirm this:

List<KGramPostingsEntry> a = new ArrayList<KGramPostingsEntry>();
List<KGramPostingsEntry> b = new ArrayList<KGramPostingsEntry>();
KGramPostingsEntry entry = new KGramPostingsEntry(1);
a.add(entry);
b.add(entry);

assertTrue(a.containsAll(b));

. . , ArrayList , add(), . , List ( tokenID), containsAll() . equals(), , ? , value , , - ( tokenID, ).

? , ?

+4
2

equals Object:

public boolean equals(Object obj)

(). , :

public boolean equals(KGramPostingsEntry other)

, KGramPostingsEntry, Object.equals, Object. , , , .

ArrayList equals, Object.equals. , , .

, : equals Object:

public boolean equals(Object obj) {
    if(obj == null || !(obj instanceof KGramPostingsEntry)) {
        return false;
    }
    KGramPostingsEntry other = (KGramPostingsEntry) obj;
    if(other.tokenID == this.tokenID) {
        return true;
    }
    return false;
}
+3

equals .

public boolean equals(Object that) {
    // ..
}
+4

Source: https://habr.com/ru/post/1696360/


All Articles