0

I think I am doing something very inefficient here, but I am trying to make a test method that checks if my containsOpposites method works. I believe the containsOpposites method does work but the main method only returns true, even if the array contains no opposite elements. What am I doing wrong?

boolean containsOpposites(int[] a) {
    for (int i=0;i<a.length; i++){
        for (int k= i+1; k<a.length; k++){

            if (a[i]== -a[k]){ return true;

            }

        }
    }

    return false;

}

   String test (int []a) {
    if (containsOpposites(a)) {return "true";}
    else return  "false";
}

public void main (String[] args) {
     int []l = new int[10]; /*this array contains no negative elements but the test 
     method return true*/
     l[0]=1;  
     l[1]=2;  
     l[2]=3;  
     l[3]=2;  

    System.out.println("" + test(l));

}
tim
  • 467
  • 5
  • 12

1 Answers1

2

When you do this int []l = new int[10]; you end up with an array that looks like [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]. You then overwrite the first 4 elements, but the remaining 6 are still 0. Since -0 == 0 evaluates to true, your code thinks there are opposites.

See this question about how Java initializes arrays depending on the data type.

Community
  • 1
  • 1
Mike B
  • 5,390
  • 2
  • 23
  • 45