我可以使用包含A或列表< A>的类型安全地图吗? [英] Can I have a type safe map that either contains A or List<A>?
问题描述
我需要一个Map容器,它包含一个
Item Object
或
列表与LT;项目>对象
作为它的值,我可以在不投射的情况下得到它,有可能吗? $ b
简短回答: //en.wikipedia.org/wiki/Union_%28computer_science%29rel =nofollow>联合类型在Java中不存在。为了获得编译时类型检查,你可以做的最接近的事情是创建一个包含 和的自定义包装类的列表 或$
public class UnionListWrapper< A> {
检查(在
private final A item;
private final List< A>列表;
public UnionListWrapper(A value){
item = value;
list = null;
}
public UnionListWrapper(List< A> value){
item = null;
list = value;
public Object getValue(){
if(item!= null)return item;
else返回列表;
$ b至少你不能 create 这个类的实例不是A
或者是List< A>
,但是获取值仍然必须是Object
,以及相关的投射。这可能会变得非常笨拙,总体来说它可能不值得。
实际上,我可能只需要一个
List< Object>
附带一些意见,非常小心接受哪些数据类型。问题是即使运行时检查(次优)也不可能,因为Java的通用擦除意味着你不能执行 instanceofList
>的泛型参数上加倍)。I need a Map container that contains either an
Item Object
or
List<Item> Object
as its value, and I can get it out without casting, is it possible?
解决方案Short answer: No.
Union types don't exist in Java. The closest thing you could do in order to get compile-time type checking would be to create list of some custom wrapper class which contained either an
A
or aList<A>
, something like the following:public class UnionListWrapper<A> { private final A item; private final List<A> list; public UnionListWrapper(A value) { item = value; list = null; } public UnionListWrapper(List<A> value) { item = null; list = value; } public Object getValue() { if (item != null) return item; else return list; } }
At least you wouldn't be able to create instances of this class that weren't either an
A
or aList<A>
, but getting the value back out would still have to just beObject
, with associated casting. This could get quite clumsy, and on the whole it's probably not worth it.In practice I'd probably just have a
List<Object>
with some comments around being very careful about what data types are accepted. The problem is that even run-time checks (sub-optimal) aren't going to be possible, since Java's generic erasure means that you can't do aninstanceof A
check at runtime (doubly so on the generic parameter of theList
).这篇关于我可以使用包含A或列表< A>的类型安全地图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!