I have been using a Collection
of number values and have implemented some related functionality (mapping x->y values, etc). So far I have made use of generics to allow any subclass of Number
in the Collection
.
In this particular class I keep running into the problem that there is no easy way to cast to the generic. The usual methods like Double.valueOf()
cannot be invoked because Number
does not provide such a method.
Is there a good way around this?
I have found this post and thought that would solve it, but I cannot pass the Class.class
parameter to it.
public class myList<T extends Number> extends Collection<T> {
@Override
public boolean add(T value){
// this is no problem
}
// What I want to do:
public boolean add(double value){
return this.add(T.valueOf(value));
}
// Using the example I found:
public void add(double value){
return this.add( (T) Ideone.parse(value, T.class) ); // no such option
}
}
Thanks in advance.
There's no way for the myList
class to be able to convert double
to T
, because T
is unknown.
One way you can solve this is to let the caller provide a function that converts from double
to T
. Here's an example:
public class myList<T extends Number> implements Collection<T> {
private DoubleFunction<T> fromDoubleFunction;
public myList(DoubleFunction<T> function) {
this.fromDoubleFunction = function;
}
public boolean add(double value) {
return this.add(this.fromDoubleFunction.apply(value));
}
//rest of code
}
That can then be used in this way:
myList<Integer> intList = new myList(d -> Double.valueOf(d).intValue());