简体   繁体   English

LinkedHashMap与不同类型的数据

[英]LinkedHashMap with different types of data

I have a LinkedHashMap 我有一个LinkedHashMap

My code 我的密码

LinkedHashMap<String, String> hmap = (LinkedHashMap<String, String>)data[0];

System.out.println("Contents of LinkedHashMap : " + hmap);

System.out.println("\nValues of map after iterating over it : ");


for (String key : hmap.keySet()) {
     System.out.println(key + ":\t" + hmap.get(key));
  }

Output: 输出:

Values of map after iterating over it : cd: PARB id_inst:PE103AA01 cd_anul: 遍历后的map值:cd:PARB id_inst:PE103AA01 cd_anul:

Error calling method: generateReport 错误调用方法:generateReport

java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String java.lang.ClassCastException:无法将java.lang.Double强制转换为java.lang.String

Contents of LinkedHashMap: LinkedHashMap的内容:

{cd=PARB,id_inst=PE103AA01, cd_anul=, mnt=276562.5, dt_den_theo=2012-01-24 00:00:00, logo=PARB.bmp, id=ISI.model.ParamRecord-1}

How can I use String and Double in my Hashmap without LinkedHashMap<String, Object> ? 如何在没有LinkedHashMap<String, Object>情况下在Hashmap使用StringDouble

我不确定您的代码是否具有通用类型<String, Object> ,如果没有,则for (String key : hmap.keySet()) {应该存在编译错误,否则,它会很好地工作。

Your issue is not that LinkedHashMap can't contain both String and Double instances. 您的问题不是LinkedHashMap不能同时包含String和Double实例。 It actually perfectly can. 实际上完全可以。 The issue is what you are doing with those values when you iterate the list. 问题是你用这些值做什么 ,当你遍历列表。 If you try to use the value as a String while it is Double you will get ClassCastException. 如果您尝试将值用作Double时将其用作String,则将获得ClassCastException。 If all you need is a String instance regarding of the actual object class you could call toString() to convert it like this: 如果您只需要一个与实际对象类有关的String实例,则可以调用toString()进行如下转换:

Object o = hmap.get(key);
String stringVal = (o == null) ? null : o.toString()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM