-4

how to compare two arrays with exact index for example

String[] test1 = {"a","b","c","d"};
String[] test2 = {"a","b","c",""};

I tried this

for (int i = 0; i < test1.length; i++) {
for (int j =  i; j < test2.length; j++) if (i==j)  if (i == j && test2[j] == "" ) {do stuff}
} 

// but always give true

now if the comparison start at index 0 for test1 it should be compared only with index 0 for test2 I want to find the empty index (for example index 3 for test2 which is related to test1 index 3) and do some stuff

I read a lot but I have some difficulties, thanks in advance.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
ced0xa
  • 3
  • 1
  • 1
    You should use `equals()` to compare String values – Hülya Jan 12 '21 at 14:58
  • If you need to compare the elements at the same index of both arrays, why are you using nested loops? One loop is enough, and then you don't need to compare indexes. Also, yes, you want to compare strings with `equals()`. – JustAnotherDeveloper Jan 12 '21 at 15:02

4 Answers4

0

Use .equals() to compare Strings. == is used for comparing primitives.

There is also no need for 2 loops.

for(int i = 0; i < test1.length; i++){
    if(test1[i].equals("")||test2[i].equals(""){
        //Do something
    }
}
Spectric
  • 30,714
  • 6
  • 20
  • 43
0

When you are comparing Strings in Java you must use EQUALS since they are objects. Also, there is no point on two loops. Just try this:

for (int i = 0; i < test1.length; i++) {
    if (test2[i].equals("") ) {do stuff}
}
  • it always gives me false, does this loop only compare the same indexes for test1 and test 2 because its important for me. – ced0xa Jan 12 '21 at 15:17
  • You are not comparing it. In this case it´s not needed because as the arrays have the same size their indexes will always be the same. And the if is true for i=3. – pabloespinosa12 Jan 12 '21 at 15:21
0

From what I understand, you want to compare two arrays that might not be the same size, and if they are not, then only compare up to the shortest size? You can do something like this:

boolean equals = true;
for(int i = 0; i < test1.length && i < test2.length; i++) {
    if(!test1[i].equals(test2[i])) {
        equals = false;
        break;
    }
}
Pieter12345
  • 1,713
  • 1
  • 11
  • 18
0

Use deepEquals() of Arrays.java :

  import java.util.Arrays;

  String[][] s1 =
        {
            {"A", "B", "C"},
            {"X", "Y", "Z"}
        };
 
 String[][] s2 =
        {
            {"A", "B", "C"},
            {"X", "Y", "Z"}
        };
 
 System.out.println("deepEquals() returns " + Arrays.deepEquals(s1, s2));

Output : deepEquals() returns true

NehaK
  • 2,639
  • 1
  • 15
  • 31