“通用方法"“绝对值"爪哇 [英] "generic method" "absolute value" java

查看:56
本文介绍了“通用方法"“绝对值"爪哇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的学生做一个愚蠢的例子,但不知道我是否能做到我的想法

I want to make a stupid example for my students, but a don´t know if I can do what I´m thinking

我想用泛型做 abs 方法.

I want to do the abs method with generics.

我的想法与此类似:

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) 不是一个类型

eclipse says that (T) is not a Type

推荐答案

你的动机是返回一个与调用对象相同类型的对象.

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();

你实际上不得不说

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

但这行不通,因为 T 在编译时是未知的,这时必须做出有关它的决定.

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);
}

并有像

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.

依赖于您正在寻找的类型推断的好例子是高阶函数(当然,Java 没有一流的函数,因此您必须使用单一方法接口对它们进行建模).然后你可以,例如,

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);

不完全是初学者的东西,尤其是当还显示了实现时,但也许它适合您的课程.请注意,当 Java 8 发布时,这种东西会变得非常突出.

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.

这篇关于“通用方法"“绝对值"爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆