首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >处理LinkedHashMap<String、LinkedHashMap>的泛型

处理LinkedHashMap<String、LinkedHashMap>的泛型
EN

Stack Overflow用户
提问于 2018-05-05 15:26:23
回答 1查看 668关注 0票数 0

我在泛型方面从来没有这么好过,但我使用了SnakeYaml。有没有办法让我修复这段代码?

代码语言:javascript
复制
public class MyService{
private static Map<String, LinkedHashMap> myYamlMap;

public static void filter(Map<String, String>){
    //myYaml map reads the YAML File using SnakeYaml
    //Snake Yaml returns data in this format <String,LinkedHashMap>
    Yaml yaml = new Yaml(); 
    Object object = yaml.load(reader); 
    Map<String, LinkedHashMap> myYamlMap = (Map<String, LinkedHashMap>)object; 

    LinkedHashMap<String, LinkedHashMap> mainMap = (LinkedHashMap<String, LinkedHashMap>)myYamlMap.get("sample");
}

},并逃脱此编译时警告?

代码语言:javascript
复制
Multiple markers at this line
    - Line breakpoint:MyService [line: 69] - filter(Map<String, String>)
    - Type safety: Unchecked cast from LinkedHashMap to LinkedHashMap<String,LinkedHashMap>
    - LinkedHashMap is a raw type. References to generic type LinkedHashMap<K,V> should be 
     parameterized
    - LinkedHashMap is a raw type. References to generic type LinkedHashMap<K,V> should be 
     parameterized

Snakeyaml..uses LinkedHashMap在它的构造中,我想摆脱造型。

EN

回答 1

Stack Overflow用户

发布于 2018-05-05 16:14:36

给定您的代码:

代码语言:javascript
复制
private static Map<String, LinkedHashMap> myYamlMap;
LinkedHashMap<String, LinkedHashMap> mainMap = (LinkedHashMap<String, LinkedHashMap>)myYamlMap.get("sample");

这没有任何意义。

代码语言:javascript
复制
private static Map<String, LinkedHashMap> myYamlMap;

这可能应该是

代码语言:javascript
复制
private static Map<String, Map<Key, Value>;
myYamlMap = new LinkedHashMap<String, Map<Key, Value>>;
myYamlMap.put("key1", new LinkedHashMap<Key,Value>();

对于某些没有在代码中指定的KeyValue类型...或者更复杂的东西--见下文

代码语言:javascript
复制
LinkedHashMap<String, LinkedHashMap> mainMap = (LinkedHashMap<String, LinkedHashMap>)myYamlMap.get("sample");

您在这里使用get似乎暗示myYamlMap应该是

代码语言:javascript
复制
private static Map<String, Map<String, Map<Key, Value>> myYamlMap;
myYamlMap = new LinkedHashMap<String, Map<String, Map<Key,Value>>>;
Map<Key,Value> temp = new LinkedHashMap<Key,Value>();
temp.put(k1, value1);
myYamlMap.put("sample", temp);

因为您似乎希望get()从外部集合中返回一个Map<String,Map<Key,Value>>

现在你可以做

代码语言:javascript
复制
Map<String, Map<Key,Value>> mainMap = myYamlMap.get("sample");

使用Map接口的原因是,在您的代码中没有使用特定于LinkedHashMap的方法,因此声明都应该只使用Map<...>,除非实例化映射。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50186883

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档