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
Post a Comment