Methods for an interface with a variable number of parameters

I would like to ask you whether it is possible in Java to have a method declaration in an interface, but I want certain methods to have a variable number of input parameters (for example, all the same types). I thought something like this:

public interface EqualsCriteria { public boolean isEqual(String... paramsToCheck); // this is not equals(Object obj) !!! } 

And one class implements the same criteria as, 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 need 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 more complicated, but it can be useful for me.

+4
source share
3 answers

The best way:

 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())); } } 

Thus, even if the number of rows changes, it will still work.

+1
source

You can achieve this by checking the size of the array

 public class CommonEquals implements EqualsCriteria { private String name; private String surname; .... @Override public boolean isEqual(String .. arr) { if (arr.length != 2) { throw new IllegalArgumentException(); // or return false } return name.equals(arr[0]) && surname.equals(arr[1]); } } 

EDIT

The only way to make it more readable (extract the common part)

 @Override public boolean isEqual(String oName, String oSurname, String .. arr) { return name.equals(oName) && surname.equals(oSurname); //ignore arr since you don't need it } 

And for another class you will have

 @Override public boolean isEqual(String otherName, String otherSurname, String .. arr) { return name.equals(otherName) && surname.equals(otherSurname) && passport.equals(arr[0]); } 
+3
source

public interface EqualsCriteria {

public boolean isEqual (ArrayList parameter);

}

in a resume, you cannot change the number of function parameters because it is not an override.

0
source

Source: https://habr.com/ru/post/1495773/


All Articles