I´m trying to find similar rows in multiple two-dimensional arrays as it was described in my previous post. For the below-given example, the answer is false, true, although it should be false, false.
Another very important question is how to adjust this code to arrays with the different number of rows.
I appreciate very much any help. Thanks.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
ArrayList<Integer[]> array1 = new ArrayList<Integer[]>();
ArrayList<Integer[]> array2 = new ArrayList<Integer[]>();
ArrayList<Integer[]> array3 = new ArrayList<Integer[]>();
array1.add(new Integer[]{1,2,3}); array1.add(new Integer[]{1,0,3});
array2.add(new Integer[]{1,0,3}); array2.add(new Integer[]{0,0,3});
array3.add(new Integer[]{1,2,3}); array3.add(new Integer[]{0,3,3});
for (int i=0; i<array1.size(); i++) {
boolean answ = equalRows(array1.get(i),array2.get(i),array3.get(i));
System.out.println(answ);
}
}
static class Row extends Object {
private int value;
public Row(int val) {
this.value = val;
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if((obj == null) || (obj.getClass() != this.getClass()))
return false;
// object must be Row at this point
Row row = (Row)obj;
return (value == row.value);
}
@Override
public int hashCode () {
return this.value;
}
}
private static Map<Row, Integer> map(Integer[] row) {
Map<Row, Integer> rowMap = new HashMap<Row, Integer>();
for (int i=0; i<row.length; i++)
rowMap.put(new Row(row[i]), i);
return rowMap;
}
private static boolean equalRows(Integer[] row1, Integer[] row2, Integer[] row3){
Map<Row, Integer> map1 = map(row1);
Map<Row, Integer> map2 = map(row2);
for (int i=0; i<row3.length; i++){
Row row = new Row(row3[i]);
Integer result1 = map1.get(row);
Integer result2 = map2.get(row);
if (result1 == null || result2 == null) {
return false;
}
}
return true;
}
}
Edit#1
In the first test I´m comparing {1,2,3}, {1,0,3} and {1,2,3}. In the second: {1,0,3}, {0,0,3}, {0,3,3}. The problem with the second row is that {0,0,3} and {0,3,3} are tackled as {0,3}. I don´t know how to modify the code to deferentiate between {0,0,3} and {0,3,3} (I still should use HashMap).
Edit#2
The idea is that first I take rows from array1 and array2 and I put them into maps. Then I take a row from array3 and try to find it in maps. If I can´t find it in any of these maps, then it means that rows are not similar.
To compare two arrays, ignoring nulls you can have
The problem you have is that array3 is being used to determine which rows to compare.
In the first test you are comparing rows 1,2,3 and the second test you are comparing rows 0 and 3. The first test should be false and the second should be true.
I found the issue by stepping through your code in a debugger. I suggest you do the same.
I would also use
int[]instead ofInteger[]