equals

——-

Every class has one equals() method.

r1.equals(r2); r1 == r2;

Now, if the content of the object (same or not same) pointed by r1 and r2 are the same then the first statement is true. The second statement is true iff both point to the same object. Many classes define equals() to compare the contents of the two objects.

Four degrees of equality

————————–

1. Reference equality, ==

2. Shallow Strutural equality, ie fields ==

3. Deep structural equality, ie fields equals()

4. Logical equality

a. Fractions 1/3 and 2/6 are “equals” from a mathematical point of view

b. “Set” objects are “equals” if they contain the same elements, irrelevent of the order.

public class SList{ public boolean equals(SList other){ if (size != other.size) return false; // two SLists with different size cannot be same SListNode n1 = head; // initial offsets of both the SLists SListNode n2 = other.head; while(n1 != null){ if(!n1.item.equals(n2.item)){ return false; } n1 = n1.next; n2 = n2.next; } // end of while return true; } }