user3439273
user3439273

Reputation: 125

How do I compare two arrays?

How do I compare two arrays, in size AND in content?

In the class with the constructor I created this equals() method:

public boolean equals(VarArray otherArray) {
    if ((myInts.equals(otherArray)))) { 
        return true;
    }else {
        return false;
    }
}

This is how I have it in the class I'm testing with and I still get false instead of true:

int[] array = {0,1,2,3,4,5,6,7,8,9,10};

VarArray testArray = new VarArray(array);
VarArray testArray2 = new VarArray(array);

System.out.println("\n" + testArray.equals(testArray2)); // should be true

Upvotes: 2

Views: 77

Answers (4)

aviundefined
aviundefined

Reputation: 872

Your implmentaion of equals is wrong. In your case it will call the equals method of array which will compare the object instance of both the array which are different. Correct implementation of equals method will look like this:

public class VarArray
{

    private int[] myInts = null;

    private int[] getMyInts()
    {
        return myInts;
    }

    public VarArray(int[] arr)
    {
        myInts = arr;
    }

    public boolean equals(VarArray otherArray)
    {
        if (myInts == null && otherArray == null)
        {
            return true;
        }

        if (myInts == null || otherArray == null)
        {
            return false;
        }

        if (myInts.length != otherArray.getMyInts().length)
        {
            return false;
        }

        int[] otherMyInts = otherArray.getMyInts();
        for (int i = 0; i < myInts.length; i++)
        {
            if (myInts[i] != otherMyInts[i])
            {
                return false;
            }
        }

        return true;
    }
}

or if you don't want to write such code, which is in my opinion waste of time and energy use java.util.Arrays and use this code

int[] array = {0,1,2,3,4,5,6,7,8,9,10};
        int[] array1 = {0,1,2,3,4,5,6,7,8,9,10};
boolean isEqual = Arrays.equals(array, array1);
        System.out.println(isEqual);

Upvotes: 0

Makoto
Makoto

Reputation: 106508

Arrays.deepEquals() will perform deep comparison, which will also check for any nested elements.

public boolean equals(VarArray otherArray) {
    return Arrays.deepEquals(myInts, otherArray.getInts());
}

Upvotes: 0

user692168
user692168

Reputation:

otherArray is of type VarArray and you're comparing it to an array of ints. What you want is:

public boolean equals(VarArray otherArray) {
   return Arrays.equals(myInts, otherArray.myInts);
}

Upvotes: 0

Abiel Paltao
Abiel Paltao

Reputation: 315

use Arrays.equals(testArray, testArray2);

Upvotes: 4

Related Questions