"general method" "absolute value" java

I want to make a stupid example for my students, but I don’t know if I can do what I think.

I want to use the abs method with generics.

My idea is something like this:

public class MiMath {
  public static <T extends Number> T abs(T objeto) {
    if (objeto.doubleValue()<0)
        return (T) -objeto.doubleValue();
    else
        return  objeto;
  }
}

in this line

return (T) -objeto.doubleValue(); 

eclipse says (T) is not a type

+1
source share
3 answers

Your motivation is to return an object of the same type as the one with which it was called.

Unfortunately, Generics cannot help you. On your line

return (T) -objeto.doubleValue();

you really need to say

return new T(-objecto.doubleValue());

but this cannot work, because T is not known at compile time, and that is when a decision must be made on this.

, ,

public interface AbsEvaluator<N extends Number> {
    N abs(N n);
}

,

AbsEvaluator<Integer> intAbs = 
  new AbsEvaluator<Integer>() { public Integer abs(Integer n) { return -n; }};

, .

, , , (, Java , ). , ,

<T,U,V> Function<T, V> compose(Function<U, V> g, Function<T, U> f);

, , , , . , Java 8.

+1

, , (T), , T.valueOf() - .

, ( , , , ).

+1

(T) .

, , return.

-1

Source: https://habr.com/ru/post/1653164/


All Articles