0

I know I could use the contains() method, but I can't figure out how to use it for a two dimensional array and how to return something.

Right now my code looks like this:

public class Array {

  public static void main(String[] args) {
    int z = 2;
    int[][] data = new int[1][4];
    data[0][0] = 0;
    data[0][1] = 3;
    data[0][2] = 2;
    data[0][3] = 6;

    for (int i = 0; i < data[0].length; i++) {
      if (data[0][i] == z) {
        System.out.println("Array data has z");
      }
    }
  }
}

Checking with a loop works, but we were advised to use the contains method.

But how can I use the contains method in my case?

Maroun
  • 94,125
  • 30
  • 188
  • 241
marvin
  • 43
  • 1
  • 6

1 Answers1

2

The method contains() is valid for Collections, not for Array.

In order to use this method, you need to convert your arrays into Collections first. As you have a two-dimensional array, I suggest you loop through it and analyze each of its one-dimensional subarrays to look for the desired value.

public boolean containsValue(int[][] data, int z) {
    for (int i = 0; i < data.length; i++) {
        if (Arrays.asList(data[i]).contains(z)) {
            return true;
        }
    }
    return false;
}

Another approach would be to use ArrayUtils.contains() method if you are using it in your project, as already shown here.

Finally, you can perform an O(n²) comparison with two for blocks to search for the desired value without the overhead of converting your array into a list, as stated above. However, I believe the approach shown in the code snippet above will be faster.

Community
  • 1
  • 1
Bruno Toffolo
  • 1,504
  • 19
  • 24