Comparing User Defined OBJECTS

  1. Recall that objects are stored as follows:

  2. Comparing "equality" of 2 user-defined objects x1 and x2 :

    Test Outcome of the test
      x1 == x2     true if x1 and x2 are aliases  
      x1 != x2     true if x1 and x2 are not aliases  
      x1.equals(x2)     Outcome can be defined by user  

  3. Example of using == test:

    Example: comparing 2 GeneralizedCounter objects with ==
       public class myExample
       {
          public static void main(String argv[])
          {
             GeneralizedCounter x1 = new GeneralizedCounter(6);
             GeneralizedCounter x2 = new GeneralizedCounter(6);
             GeneralizedCounter x3 = x2; (x2 & x3 are aliases)
          
             if ( x1 == x2 ) ...  test result will be false
             if ( x2 == x3 ) ...  test result will be true
          }
       }
    

  4. The DEFAULT equals test:

    Example: default "equals" test is the same as "=="
       public class myExample
       {
          public static void main(String argv[])
          {
             GeneralizedCounter x1 = new GeneralizedCounter(6);
             GeneralizedCounter x2 = new GeneralizedCounter(6);
             GeneralizedCounter x3 = x2; (x2 & x3 are aliases)
          
             if ( x1.equals(x2) ) ...  DEFAULT test result is false
             if ( x2.equals(x3) ) ...  DEFAULT test result is true
          }
       }
    

  5. Using your own equals test:

    To use your own "equals" test, you must define an equal() method in your class:
    
       public class GeneralizedCounter
       {
          int maxAcceptableNumber;
          int count[];    // integer array to keep the count for each number
    
          ... (other variables and methods - not repeated to save space)
    
          public boolean equals(GeneralizedCounter a)
          {
    	 // This object was defined by the USER
             // So the USER decides when 2 GeneralizedCounters are equal.
             // My choice: same number of counters & all counters are equal
    
    	 int i;
    
    	 if ( maxAcceptableNumber != a.maxAcceptableNumber )
    	    return(false);	// different number of counters, reject
    
    	 for ( i = 1; i <= maxAcceptableNumber; i = i+1 )
    	 {  if ( count[i] != a.count[i] )
    	       return(false);   // different value in counter
    	 }
    
    	 return(true);
          }
       }
    
       public class myExample
       {
          public static void main(String argv[])
          {
             GeneralizedCounter x1 = new GeneralizedCounter(6);
             GeneralizedCounter x2 = new GeneralizedCounter(6);
             GeneralizedCounter x3 = x2; (x2 & x3 are aliases)
          
             if ( x1.equals(x2) ) ...  use user defined test
          }
       }
    

     

    Here is a DEMO program: click here

    You also need a NEW GeneralizedCounter class with the equals method defined: click here