java - Can a method receive an Array or Iterable? -
the loop (as foreach) accepts arrays or iterables, there input type covers both, or have write overloaded method? can have in java:
public void serialize (arrayoriterable xxx){ (object x: xxx) { x.dosomething() } }
or choice having repeated code?
public void serialize (object[] xxx){ (object x: xxx) { x.dosomething() } } public void serialize (iterable xxx){ (object x: xxx) { x.dosomething() } }
edit conclusions
even better, class structure abstract class , implementation can define behaviour arrays in asbtract class , implementations need have 1 method overwritten.
public abstract class serializer { public final void serialize(object[] input) { serialize(arrays.sslist(input)); } public abstract void serialize(iterable input); }
java, unfortunately, doesn't have reasonable syntax of doing this, iterable
s , arrays discrete types. however, can improve current code remove duplication of dosomething()
calls wrapping array list
interface calling arrays.aslist
:
public void serialize (object[] xxx){ serialize (arrays.aslist(xxx)); } public void serialize (iterable xxx){ (object x: xxx) { x.dosomething() } }
Comments
Post a Comment