Patrick
Patrick

Reputation: 3021

Java 2 dimensional integer array check existence

I have a two dimensional array in java. Here I want to check the existence of a pair of values. But I got false all the time.

int[][] test_use = new int[1][2];
test_use[0][0] = 2;
test_use[0][1] = 6;
int[][] constraints = new int[1][2];
constraints[0][0] = 2;
constraints[0][1] = 6;
System.out.println(Arrays.asList(constraints).contains(test_use));

Do you guys have any ideas for this issue? How could I check its existence properly. Thank you so much!

Upvotes: 0

Views: 76

Answers (3)

Ramsay Domloge
Ramsay Domloge

Reputation: 705

The contains() method on Java collections uses the equals() method on each contained object, to check whether the comparison object is contained.

The equals method for an array just inherits from Object, which compares whether the objects are the same object, rather than whether they are logically-equivalent.

You are creating 2 different arrays and comparing them with equals() and they are not the same object, so their equals method is returning false, so contains returns false.

As such, this prints false too:

System.out.println(new int[]{i,j}.equals(new int[]{i,j}));

If you want to get the right result, you can implement the comparison yourself:

int[][] arr = new int[1][2];
arr[0] = new int[]{2,6};
List<int[]> l = Arrays.asList(arr);
for (int[] check : l) {
    if(check[0] == 2 && check[1] == 6) {
        System.out.println(true);
        return;
    }
}
System.out.println(false);

Upvotes: 1

Nicola Miotto
Nicola Miotto

Reputation: 3706

You could use a function like this, defined in a class of your preference:

public bool contains(int[][] container, int[][] isContained){
 bool miss = false;
 for(int i = 0; i < isContained.length && !miss; i++){
     for(int j = 0; j < isContained[i].length && !miss; j++){
        if(container.length > i && container[i].length > j){
            if(container[i][j] == isContained[i][j]) {
               continue;
            }
        }
        miss = true;
     }
 }

 return !miss;

}

Upvotes: 0

SpaceCowboy
SpaceCowboy

Reputation: 563

Something like this should get you what you want.

System.out.println(Arrays.asList(constraints).contains(test_use[0][1]));

Upvotes: 0

Related Questions