我有一个问题,如果我们定义hashMap来接收字符串键和字符串值,但由于某种原因,我们需要在将其转换为字符串(obj.toString())后将其存储为值。在此示例中,如果我遍历hashMap并需要访问它的字段,我无法访问它,因为它被转换为字符串,那么解决方案是什么?谢谢
HashMap<String, String> hashMapObj = new HashMap<String, String>();
hashMapObj.put("hil", "aii");
hashMapObj.put("hil1", "ai1");
hashMapObj.put("hil2", "ais2");
hashMapObj.put("hi3", "aisi3");
hashMapObj.put("hil4", "aii4");
Employee obj = new Employee(1, "Bill Hill ", 7);
int[] arr = {1,2,3,4,5,6,6,7,7};
hashMapObj.put("emp1", obj.toString());
hashMapObj.put( Integer.toString(1) , obj.toString() );
hashMapObj.put("arr" , Arrays.toString(arr));
for(HashMap.Entry< String , String> x : hashMapObj.entrySet()){
String key = x.getKey();
System.out.println("key ===> "+ key);
System.out.println("j ===> " + hashMapObj.get("1"));
Object e = (Object) hashMapObj.get("1");
System.out.println(e);
}发布于 2019-10-10 23:43:48
不要使用HashMap<String, String>();,而是使用HashMap<String, Object>();,并且不要使用toString()方法转换对象。如果你这样做了,如果你使用get,你总是会得到一个对象。然后,可以轻松地将该对象传递给系统println方法。
发布于 2019-10-10 23:44:48
它的解决方案是什么?
有两种解决方案。
第一个解决方案是从一开始就不做。将对象本身存储为值;即作为Map<String, YourClass>,这是最简单的解决方案,也是计算效率最高的解决方案。
第二个解决方案还有更多的工作要实现:
YourClass.toString()方法,以便对重建对象所需的所有信息进行编码。这通常包括对象字段的值。字符串表示必须是明确的,并且应该易于解析。static YourClass fromString(String s) {...},您可以使用它来解析toString()输出,并根据它重新构造对象。您可以使用JSON作为字符串表示,并使用JSON绑定库(如GSON或Jackson )进行对象<->字符串转换。
请注意这一点:
YourClass y = (YourClass) map.get("1");行不通的。不能将String转换为YourClass。您需要编写一些Java代码来从String重新创建YourClass实例。
https://stackoverflow.com/questions/58326471
复制相似问题