Methods for an interface with a variable number of parameters
interface, java
Solution
A better way would be:
public interface EqualsCriteria {
public boolean isEqual(EqualsCriteria other);
public String[] getParam();
// this is not equals(Object obj) !!!
}
And then:
public class CommonEquals implements EqualsCriteria {
private String name;
private String surname;
@Override
public boolean isEqual(EqualsCriteria other) {
if(other==null) return false;
return Arrays.asList(getParam()).equals(Arrays.asList(other.getParam()));
}
}
This way, even if number of Strings changes, still it will work.
Problem
I'd like to ask you if it's possible in Java to have a declaration of a method in a interface but, I want that the methods defined could have a variable number of input parameters (for example, all of the same type). I was thinking in something like this: ``` public interface EqualsCriteria { public boolean isEqual(String... paramsToCheck); // this is not equals(Object obj) !!! } ``` And one class implements that equal criteria like, for example: ``` public class CommonEquals implements EqualsCriteria { private String name; private String surname; .... @Override public boolean isEqual(String otherName, String otherSurname) { return name.equals(otherName) && surname.equals(otherSurname); } } ``` But maybe, I want other criteria in another part of the code, something like this ``` public class SpecialEquals implements EqualsCriteria { .... @Override public boolean isEqual(String otherName, String otherSurname, String passport) { return name.equals(otherName) && surname.equals(otherSurname) && passport.equals(passport); } } ``` PS: Actually my problem is a little bit more complicated, but this could be useful to me.