泛型和继承:需要一个复杂的Map实例 [英] Generics and inheritance: need a complex Map instance

查看:121
本文介绍了泛型和继承:需要一个复杂的Map实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public abstract class Mother {
}

public class Daughter extends Mother {
}

public class Son extends Mother {
}

我需要一个地图哪些键是女儿 Son classes,哪些值是这两个类之一的对象的列表,分别

I need a Map which keys are one of Daughter or Son classes, and which values are lists of objects of one of those two classes, respectively.

例如: p>



For example:

/* 1. */ map.put(Daughter.class, new ArrayList<Daughter>()); // should compile
/* 2. */ map.put(Son.class, new ArrayList<Son>()); // should compile
/* 3. */ map.put(Daughter.class, new ArrayList<Son>()); // should not compile
/* 4. */ map.put(Son.class, new ArrayList<Daughter>()); // should not compile

我尝试过 Map< Class< T extends Mother> ,列表< T> ,但不编译。

Map< Class<?扩展母亲>,列表<?扩展母亲> 确实编译,但情况 3。 4。 do

Map<Class<? extends Mother>, List<? extends Mother>> does compile, but the cases 3. and 4. do compile too while then shouldn't.

是否有可能?

推荐答案

我不认为可以在类型中进行编码,我会用自定义类来实现

I don't think it's possible to encode this in the type, I'd do it with a custom class

class ClassMap<T> {
  private Map<Class<? extends T>, List<? extends T>> backingMap = new HashMap<>();

  public <E extends T> void put(Class<E> cls, List<E> value) {
    backingMap.put(cls, value);
  }

  @SuppressWarnings("unchecked")
  public <E extends T> List<E> get(Class<E> cls) {
    return (List<E>)backingMap.get(cls);
  }
}

只要你呃不要泄漏这个类外的 backingMap 引用。

It's safe to suppress warnings here as long as you don't leak the backingMap reference outside this class.

这篇关于泛型和继承:需要一个复杂的Map实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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