Popokoko
Popokoko

Reputation: 6543

Java: Implementing equals method for comparing two double[][] arrays

I'm trying to implement the equals method in my class.. notice: the '_data' property is an double[][] array im trying to compare between the two objects.

anyway it compiles and everything but i always get a false answer and this can't be because both arrays are same :o

am i doing something wrong? is there any other easy way? (only with using equals from object class!!)

My code (JAVA):

public boolean equals(Object obj) {
    if (!(obj instanceof MyClass)) {
        return false;
    }

    MyClass myObj = (MyClass) obj;
    return this._data.equals(myObj._data);
}

Upvotes: 1

Views: 2416

Answers (5)

duffymo
duffymo

Reputation: 308763

Joshua Bloch tells you how to implement equals and hashCode (they must be done in tandem) in chapter 3 of "Effective Java". That should tell you all you need to know in order to override equals for your class.

Upvotes: 0

cabreracanal
cabreracanal

Reputation: 934

I would override the equals method in your MyClass class.

@Override
public boolean equals(Object obj) {//if you insist in using an Object as argument instead of double[][]
   if (!(obj instanceof MyClass)) {
      return false;
   }

   MyClass myObj = (MyClass) obj;
   if(_data.length == myObj._data.length){
      for(int i=0; i<_data.length; i++){
         if(_data[i].length == myObj._data[i].length){
            for(int j=0; j<_data[i].length; j++){
               if(_data[i][j] != myObj._data[i][j]){
                  return false;
               }
            }
         }else{
            return false;
         }
      }
   }else{
      return false;
   }
   return true;
}

This code considers the case you will have a two dimensional array but not a square matrix. i.e. first row with three elements, second row with 27 elements, third row with N elements... For example, a test case:

    double[][] first= new double[5][3];
    double[][] second= new double[5][3];
    for(int i=0; i<first.length; i++){
        for(int j=0; j<first[i].length; j++){
            first[i][j] = 5;
        }
    }
    for(int i=0; i<second.length; i++){
        for(int j=0; j<second[i].length; j++){
            second[i][j] = 5;
        }
    }
    second[4][2] = 2;

    MyClass c1 = new MyClass(first);
    MyClass c2 = new MyClass(second);

    System.out.println("Equals: "+c1.equals(c2));

Upvotes: 0

Michaeldcooney
Michaeldcooney

Reputation: 1445

You can take a look at this post which describes the deepEquals method: Java Arrays.equals() returns false for two dimensional arrays

Upvotes: 2

Baptiste Wicht
Baptiste Wicht

Reputation: 7663

Use

Arrays.deepEquals(this._data, myObj._data) 

to make the test on the arrays.

Upvotes: 8

Bozho
Bozho

Reputation: 597076

Use Arrays.deepEquals(data, myObj._data)

Upvotes: 5

Related Questions