-1

varargs defined as String... can be accessed like a String[].

But the equals method returns false when comparing 2 String arrays, one passed as varargs and other as String[].

Is there a direct way to test for the equality of content in the two arrays ? For instance using the Arrays.equals method.

Here, is the example:

public String[] getParams() {
    return params;
}

public void testForEquality(String... param) {
    if (Arrays.equals(getParams(), param)) {
         // do something
    }        
}
hemanik
  • 965
  • 3
  • 14
  • 33
  • how you test them, can you show us your code please? – Youcef LAIDANI Jan 10 '18 at 14:24
  • you need to test the Strings in the array. if you just compare two arrays, you'll do a referential comparison – Stultuske Jan 10 '18 at 14:25
  • 2
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a [mcve]. Use the [edit] link to improve your *question* - do not add more information via comments. Thanks! – GhostCat Jan 10 '18 at 14:29
  • 1
    @Stultuske, I intend to compare the content of the 2 arrays here. – hemanik Jan 10 '18 at 14:30
  • 1
    And Arrays.equals() does exactly that. So as written - no idea what is really going in your code - as you did not provide an [mcve] that would enable us to understand that. – GhostCat Jan 10 '18 at 14:36

1 Answers1

3

I've made a little test and I think you are missing something thus my test passes as expected.

private String[] params = {"1", "2", "3"};

public String[] getParams() {
    return params;
}

public boolean testForEquality(String... param) {
    return Arrays.equals(getParams(), param);
}    

And then the tests are:

System.out.println(testForEquality("1", "2", "3"));
System.out.println(testForEquality("-1", "2", "3"));
System.out.println();
System.out.println(testForEquality(new String[] {"1", "2", "3"}));
System.out.println(testForEquality(new String[] {"2", "3"}));

And then the output:

true
false

true
false
dbl
  • 1,109
  • 9
  • 17