2

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.

Sonke W
  • 107
  • 6

2 Answers2

2

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());
ernest_k
  • 44,416
  • 5
  • 53
  • 99
1

Provide a DoubleFunction<T> to your class as a constructor parameter.

public class myList<T extends Number> extends Collection<T> { 
  private final DoubleFunction<T> theDoubleFn;

  public myList(DoubleFunction<T> theDoubleFn) {
    this.theDoubleFn = theDoubleFn;
  }

  // ...

Then invoke:

return this.add(theDoubleFn.apply(value));

in the method.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Unrelated: if you have a minute or two, please have a look at https://stackoverflow.com/a/55650516/1531124 and let me know what you think about the two answers given on that question. – GhostCat Apr 13 '19 at 11:41