我可以使用包含A或列表< A>的类型安全地图吗? [英] Can I have a type safe map that either contains A or List<A>?

查看:86
本文介绍了我可以使用包含A或列表< A>的类型安全地图吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个Map容器​​,它包含一个


Item Object




列表与LT;项目>对象


作为它的值,我可以在不投射的情况下得到它,有可能吗? $ b

解决方案

简短回答: //en.wikipedia.org/wiki/Union_%28computer_science%29rel =nofollow>联合类型在Java中不存在。为了获得编译时类型检查,你可以做的最接近的事情是创建一个包含 和的自定义包装类的列表 或$ List< A> ,如下所示:

  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的通用擦除意味着你不能执行 instanceof 检查(在 List >的泛型参数上加倍)。


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 a List<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 a List<A>, but getting the value back out would still have to just be Object, 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 an instanceof A check at runtime (doubly so on the generic parameter of the List).

这篇关于我可以使用包含A或列表&lt; A&gt;的类型安全地图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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