Java泛型中有没有模仿OR的方法? [英] Is there any way of imitating OR in Java Generics

查看:203
本文介绍了Java泛型中有没有模仿OR的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我改变了一些想法:





 <整数或浮点> 

...无需创建通用接口并为Integer和Float创建子类来实现它 如果没有,这样的事情可能会更有意义并且有用

 < E扩展数字> < E =(整数|浮点)> 

如果?是一个通配符,为什么我们不应该允许限制某些类型?

解决方案

这是不可能的,我几乎看不到任何价值。您使用泛型来限制类型,例如在收藏。使用运算符,您可以尽可能多地了解这两种类型的最具体的超类型, Object 在这种情况下。所以为什么不使用 Object



假设:

 列表< E扩展字符串或数字> list = // ... 

list.get的类型是什么(0)?它是字符串 还是 数字?但是你不能有这种类型的变量。它不能是 String ,它不能是 Number - 它只能是... Object 。



更新:由于您将您的示例更改为:

 <整数或浮点数> 

为什么你不会说:

 <号> 

?请注意, Number 有方法可以让你轻松地提取 floatValue() intValue()。您真的需要确切的类型吗?






请注意,您可以使用运算符:

 < E extends Serializable&可闭合的> 

这非常合理 - 您可以使用 E 需要 Serializable 可关闭。换句话说, E 必须同时扩展 Serializable 可关闭。另请参阅:使用多个类的Java泛型通配符


EDIT: I changed a bit the example for getting the idea:

Like

 <Integer or Float>

...without having to create a common interface and make a subclass for Integer and Float to implement it

If not, something like this would maybe have more sense and be useful

 <E extends Number> <E = (Integer|Float)>

If ? is a wildcard why should not we allowed to restrict certain types?

解决方案

It's not possible and I hardly see any value in it. You use generics to restrict type, e.g. in collections. With or operator you know as much about the type as much you know about the most specific supertype of both of them, Object in this case. So why not just use Object?

Hypothetical:

List<E extends String or Number> list = //...

What is the type of list.get(0)? Is it String or Number? But you cannot have a variable of such type. It cannot be String, it cannot be Number - it can only be... Object.

UPDATE: Since you changed your example in question to:

<Integer or Float>

why won't you just say:

<Number>

? Note that Number has methods that allow you to easily extract floatValue() and intValue(). Do you really need the exact type?


Note that you can use and operator:

<E extends Serializable & Closeable>

And that makes perfect sense - you can use variable of type E where either Serializable or Closeable is needed. In other words E must extend both Serializable and Closeable. See also: Java Generics Wildcarding With Multiple Classes.

这篇关于Java泛型中有没有模仿OR的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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