如何创建一个内部结构复杂的列表 [英] How to create a list with complex structure inside

查看:91
本文介绍了如何创建一个内部结构复杂的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个类:

  class Key< T1,T2> {} 
class Pair< F,S> {}

我想从 Key< T1,T2> 到列表< Pair< T1,T2>>< / code>其中T1和T2对于每个地图条目都是不同的。我试图用这种方式实现它:

  class KeyToListMap {
private Map< Key<?,?> ,List< Pair<?,?>>> myItems = new HashMap< Key <?,?>,List< Pair<?,?>>>();


public< T1,T2> List< Pair< T1,T2>> getList(Key< T1,T2> key){
if(!myItems.containsKey(key)){
myItems.put(key,new ArrayList< Pair< T1,T2>>()) ;
}
return(List< Pair< T1,T2>>)myItems.get(key);


然而,我得到了两个类型错误:

  put(test.Key<?,?>,java.util.List< test.Pair<?,?>>)在java.util.Map< test.Key<?,?>,java.util.List< test.Pair<?,?>>>不能应用于(test.Key< T1,T2>,java.util.ArrayList< test.Pair< T1,T2>>)

不可转换类型
found:java.util .LIST< test.Pair<,>?>
required:java.util.List< test.Pair< T1,T2>>

如何在不使用原始类型的情况下使用Java来表达它?

解决方案

使用

 ?在地图声明中扩展


I have the following two classes:

class Key<T1, T2> {}
class Pair<F, S> {}

I want to create a map from Key<T1, T2> to List<Pair<T1, T2>> where T1 and T2 are different for each map's entry. I am trying to implement it this way:

class KeyToListMap {
  private Map<Key<?, ?>, List<Pair<?, ?>>> myItems = new HashMap<Key<?, ?>, List<Pair<?, ?>>>();


  public<T1, T2> List<Pair<T1, T2>> getList(Key<T1, T2> key) {
    if (!myItems.containsKey(key)) {
      myItems.put(key, new ArrayList<Pair<T1, T2>>());
    }
    return (List<Pair<T1, T2>>) myItems.get(key);
  }
}

However I got two type errors:

put(test.Key<?,?>,java.util.List<test.Pair<?,?>>) in java.util.Map<test.Key<?,?>,java.util.List<test.Pair<?,?>>> cannot be applied to (test.Key<T1,T2>,java.util.ArrayList<test.Pair<T1,T2>>)

inconvertible types
found   : java.util.List<test.Pair<?,?>>
required: java.util.List<test.Pair<T1,T2>>

How can I express this in Java without resorting to using raw types?

解决方案

Use

? extends

in Map declaration

这篇关于如何创建一个内部结构复杂的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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