我有一个问题, 如果我们定义 hashMap 来接收字符串键和字符串值,但由于某种原因,我们需要将 abject 转换为字符串后将其存储为值 (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);
}
最佳答案
而不是使用 HashMap<String, String>();
使用HashMap<String, Object>();
并且不要使用 toString() 方法转换对象。如果你这样做了,那么如果你使用 get,你总是会得到一个对象。然后可以轻松地将对象传递给系统 println 方法。
关于java - 将对象转换为字符串后存储在 hashMap 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58326471/