Java泛型中有联盟吗? [英] Is there a Union in Java Generics?

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

问题描述

我可以在集合中包含两种不同的类型吗?例如,我可以有List< String U Integer>?

解决方案

简短的回答?不,你可以(当然)有一个 List 对象,但你可以把 / em>,而不仅仅是 String Integer 对象。

您可以创建一个容器对象列表,该容器对象将包含整数 String (也许通过泛型)。更麻烦一点。

  public class Contained< T> {
T getContained();
}

并实现 Contained< Integer> 包含< String>



当然,真正的问题是你为什么要这样做?我期望一个集合包含相同类型的对象,然后我可以迭代并对这些对象执行操作,而不用担心它们是什么。也许你的对象层次需要进一步思考?


Can I contain two different types in a collection? For example, can I have List< String U Integer > ?

解决方案

Short answer ? No. You can (of course) have a List of Objects, but then you can put anything in it, not just String or Integer objects.

You could create a list of container objects, and that container object would contain either an Integer or String (perhaps via generics). A little more hassle.

public class Contained<T> {
   T getContained();
}

and implement Contained<Integer> and Contained<String>.

Of course, the real question is why you want to do this ? I would expect a collection to contain objects of the same type, and then I can iterate through and perform actions on these objects without worrying what they are. Perhaps your object hierarchy needs further thought ?

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

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