Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

you can't do `T summer = 0`, nor `summer += v[k]` as there is no arbitrary sum operation for Number (e.g a method `Number add(Number);` or `<T extends Number> T add(T t);`).

though this can be solved either with types, as mentioned in another comment (https://news.ycombinator.com/item?id=32029871), or simply by providing the sum operation:

    static <T extends Number> T sum(T[] v, BinaryOperator<T> adder) {
       T summer = v[0];
       for (int i = 1; i < v.length; i++) {
          summer = adder.apply(summer, v[i]);
       }
       return summer;
    }
    
    Float[] ft = { 0f, 1f, 2f, 3f };
    // which can also be written as
    // `float z = sum(ft, Float::sum);`
    float z = sum(ft, (x, y) -> x + y);


Bingo. You could use the longValue() or doubleValue() on Number to do math on if you insisted.


{}




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: