1

我想为我的学生做一个愚蠢的例子,但不知道我是否可以做我想做的事

我想用泛型做 abs 方法。

我的想法与此类似:

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

在这条线

return (T) -objeto.doubleValue(); 

eclipse 说 (T) 不是类型

4

3 回答 3

1

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

Unfortunately, Generics cannot help you there. On your line

return (T) -objeto.doubleValue();

you would actually have to say

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

but that can't work because T is not known at compile time, and that is when the decision about it must be made.

A way to get a similar result, but with far less elegance, would be to have an interface

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

and have implementations like

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

The implementation would be exactly the same for each type, so the scheme is quite weak.

Good examples which rely on type inference of the kind you are looking for are higher-order functions (of course, Java doesn't have first-class functions, so you have to model them with one-method interfaces). Then you could, for example, have

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

Not exactly beginner's stuff, especially when implementations are also shown, but maybe it fits into your curriculum. Note that this kind of stuff will become very prominent when Java 8 gets released.

于 2014-02-14T10:49:50.110 回答
1

问题是你在这里用 (T) 做的并不是真正的演员,在幕后它使用自动装箱和调用 T.valueOf() - 泛型不知道。

作为泛型的一个很好的例子,你最好使用集合之类的东西(因为它们也是人们最有可能使用它们的地方)。

于 2014-02-14T10:51:29.537 回答
-2

The generics information (T) exists only at compile time, and is discarded after compile.

Therefore you can never cast to a generic at run time, which is what your return statement does.

于 2014-02-14T10:49:22.060 回答