Java: generic Method - add elements to vararg -


i want here, works somehow don't think solution:

class a5<t> implements a4<t> {      private final t[] elements;      a5(t... elements) {         this.elements = elements;     }       public <r> a5<r> map(function<t, r> function) {         list<r> liste = new linkedlist<>();         (t element : elements) {             liste.add(function.apply(element));         }         object[] objects = new object[liste.size()];         int counter = 0;         (r element : liste) {             objects[counter] = liste.get(counter++);         }         return new a5(objects);     } } 

for me object[] problem, cannot create r[] array. have solution it? changing ctor , signature of map not looking for. body can changed.

you cannot create generic array, unless change t[] list<t> in class a5 need create object[].

your code can simplified bit though. can use java 8 stream map elements , collect them object[] , cast object[] r[]. @suppresswarnings("unchecked") hides warnings produced unchecked cast:

class a5<t> implements a4<t> {      private final t[] elements;      a5(t... elements) {         this.elements = elements;     }      @suppresswarnings("unchecked")     public <r> a5<r> map(function<t, r> function) {         return new a5<>((r[]) arrays.stream(elements).map(function).toarray());     } } 

Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -