0

I need to compare two Integer arrays to know if they are reverse of each other or not (determined by boolean result), in most of the cases it ends up working just fine, but whenever I try to know if the following arrays are reverse of the other one it ends up giving me troubles and I don't understand why.

boolean result = true;

Integer [] a1 = {999,1000,null};

Integer [] a2 = {null,1000,999};

if (a1.length>0){                   
    for (int i=0;i<a1.length;i++){
           if (a1[i] != a2[a1.length-i-1]){
                 return result = false;
           }
    }
}else{
    result = true;
}

I noticed that if I change a little bit the values of both arrays (for example, 99 instead of 999, or 100 instead of 1000) it works.

Could somebody give me a hand with this? Thanks in advice!

Luis CP
  • 1
  • 1

1 Answers1

0

You should use the equals() method of the Integer class to compare two Integer objects: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#equals(java.lang.Object)

When you do so, you should be careful when comparing null values. And you should also check that the size of the arrays is the same, otherwise you can have problems with the indexes.

This code should do what you are looking for:

public class Kot {
  public static void main(String[] argv) {
    boolean result = true;

    Integer[] a1 = {999, 1000, null};

    Integer[] a2 = {null, 1000, 999};

    if (a1.length != a2.length) {
        result = false;
    } else if (a1.length > 0) {
        for (int i = 0; i < a1.length; i++) {
            if (a1[i] == null && a2[a1.length - i - 1] == null) {
                continue;
            }
            if (!a1[i].equals(a2[a1.length - i - 1])) {
                result = false;
            }
        }
    } else {
        result = true;
    }

    System.out.println(result);
  }
}
gjigandi
  • 486
  • 3
  • 7