Java泛型中有联盟吗? [英] Is there a Union in Java Generics?
问题描述
我可以在集合中包含两种不同的类型吗?例如,我可以有List< String U Integer>?
简短的回答?不,你可以(当然)有一个 您可以创建一个容器对象列表,该容器对象将包含 并实现 当然,真正的问题是你为什么要这样做?我期望一个集合包含相同类型的对象,然后我可以迭代并对这些对象执行操作,而不用担心它们是什么。也许你的对象层次需要进一步思考? 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 You could create a list of container objects, and that container object would contain either an and implement 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屋! List 对象
,但你可以把 / em>,而不仅仅是 String
或 Integer
对象。
整数
或 String
(也许通过泛型)。更麻烦一点。
public class Contained< T> {
T getContained();
}
Contained< Integer>
和包含< String>
。
List
of Objects
, but then you can put anything in it, not just String
or Integer
objects. Integer
or String
(perhaps via generics). A little more hassle.public class Contained<T> {
T getContained();
}
Contained<Integer>
and Contained<String>
.