简体   繁体   中英

Writing an equals method to compare two arrays

I have the following code, I believe something is off in my equals method but I can't figure out what's wrong.

public class Test {
    private double[] info;
    public Test(double[] a){
        double[] constructor = new double[a.length];        
        for (int i = 0; i < a.length; i++){
                constructor[i] = a[i];
        }       
        info = constructor;
    }

    public double[] getInfo(){      
        double[] newInfo = new double[info.length];     
        for(int i = 0; i < info.length; i++){
            newInfo[i] = info[i];
        }   
        return newInfo;
    }
    public double[] setInfo(double[] a){
        double[] setInfo = new double[a.length];    
        for(int i = 0; i < a.length; i++){
            setInfo[i] = a[i];
        }
        return info;
    }
    public boolean equals(Test x){
        return (this.info == x.info);
    }
}

and in my tester class I have the following code:

public class Tester {

    public static void main(String[] args) {
        double[] info = {5.0, 16.3, 3.5 ,79.8} 
        Test test1 = new Test();
        test 1 = new Test(info);
        Test test2 = new Test(test1.getInfo());
        System.out.print("Tests 1 and 2 are equal: " + test1.equals(test2));
    }
}

the rest of my methods seem to function correctly, but when I use my equals method and print the boolean, the console prints out false when it should print true.

You are just comparing memory references to the arrays. You should compare the contents of the arrays instead.

Do this by first comparing the length of each array, then if they match, the entire contents of the array one item at a time.

Here's one way of doing it (written without using helper/utility functions, so you understand what's going on):

public boolean equals(Test x) {

    // check if the parameter is null
    if (x == null) {
        return false;
    }

    // check if the lengths are the same
    if (this.info.length != x.info.length) {
        return false;
    }

    // check the elements in the arrays
    for (int index = 0; index < this.info.length; index++) {
        if (this.info[index] != x.info[index]) {
            return false;
        } Aominè
    }

    // if we get here, then the arrays are the same size and contain the same elements
    return true;
}

As @Aominè commented above, you could use a helper/utility function such as (but still need the null check):

public boolean equals(Test x) {

    if (x == null) {
        return false;
    }

    return Arrays.equals(this.info, x.info);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM