I am trying to compare two rows that are in different order from a 2D array, and store elements that are the same from both rows. Here's an example of what I have produced:
String[] row1 = new String[10];
String[] row2 = new String[10];
String[][] fruit = {{"apple", "banana", "kiwi"},{"kiwi", "oranges", "grapes"}};
for (int i = 0; i < fruit.length; i++ ) {
for (int j = 0; j < fruit[i].length; j++){
if(fruit[0][j].equals(fruit[1][j])) {
row1[j] = fruit[0][j];
row2[j] = fruit[1][j];
System.out.println("Match found");
}else{
System.out.println("Not found");
}
}
}
System.out.println("row1");
System.out.println(Arrays.deepToString(row1));
System.out.println("row2");
System.out.println(Arrays.deepToString(row2));
I want the row1[] and row2[] to store the elements that are the same (which is kiwi in this example). However, the problem is .equals function only detects matching patterns. The example above only prints out nulls from row1 and row2.
It should really print out:
row1
[kiwi]
row2
[kiwi]
Note: I don't want to declare... String check = "kiwi";
because the user can enter anything in the 2D array.
Any suggestions? I feel I am getting close. I saw a similar example of someone using .equals and that worked, but it was only for single arrays.
It is less confusing to put the sub-arrays into temporary (1D) arrays:
row1Temp
androw2Temp
.Output:
I don't know your requirements, but It's a little odd to put these duplicate values into two different arrays, let alone leaving so many values null. How about using an
ArrayList
to store a single copy of the matched fruit?Output:
Or even better, just store the indexes of the matches:
Output:
The limits of your for-loops have been messed up, as well as the array elements that you accessed for comparison. I guess you wanted something like this...
But you should probably describe what you want to do with the results. These fixed-size result arrays (String[10]) look dubious, and the currently sketched code can not easily be generalized for MORE than 2 rows. There is probably a MUCH more elegant solution using
Set
s andList
s ....You're logic is slightly wrong in your loop.
If you look you are comparing
then
change if statement to
Your solution is very uneffective since you don't take advantage of the optimization algorythms like hashing:
You should use a HashSet or a HashMap to find fastly if an element is contained.
In addition collections have ready methods like retainAll() to keep only the existing elements (HashSet implements Collection so it's a good candidate for your needs)