gpt4 book ai didi

java - Map of maps - 如何将内部 map 保留为 map ?

转载 作者:搜寻专家 更新时间:2023-10-31 08:21:21 31 4
gpt4 key购买 nike

我的目标是创建一个 map 的 map ,这样我就可以通过它的键检索外部 map 的信息,然后通过它们的键访问它的“内部” map 。

但是,当我得到每个内部映射时,我最初创建的映射变成了一个对象,我不能像处理外部映射那样使用键访问它的值。

向各位高手学习,我想知道如何把所有的 map 都保存为 map 。或者,这有可能吗?

这是我的锻炼计划:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MapExample {

public static void main(String[] args) {

Map<Object,String> mp=new HashMap<Object, String>();

// adding or set elements in Map by put method key and value pair
mp.put(new Integer(2), "Two");
mp.put(new Integer(1), "One");
mp.put(new Integer(3), "Three");
mp.put(new Integer(4), "Four");

Map<Object,String> mp2=new HashMap<Object, String>();
mp2.put(new Integer(2), "Two2");
mp2.put(new Integer(1), "One2");
mp2.put(new Integer(3), "Three2");
mp2.put(new Integer(4), "Four2");

Map<Object,String> mpMaps=new HashMap();

mpMaps.put("Map1",mp);
mpMaps.put("Map2",mp2);

System.out.println("This is a map of Maps: " + mpMaps);

for (int i=0;i<mpMaps.size();i++){
ArrayList a = new ArrayList(mpMaps.keySet());
Object o=a.get(i);
System.out.println("all together: " + mpMaps.size() + "each element is: " + o + " value: " + mpMaps.get(o));
}
}
}

解决方案:

   Map<Object,Map<Object,String>
Map<String, Object> mpMaps=new HashMap<String, Object>();

通过 ameer 和 sleske

最佳答案

这是似乎有效的更新代码,您需要将 map 中的 map 键入为 <String, Object>因为 mp 不是字符串,所以你不能做 <Object, String> .

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.ArrayList;

public class MapExample {

public static void main(String[] args) {

Map<Object,String> mp=new HashMap<Object, String>();

// adding or set elements in Map by put method key and value pair
mp.put(new Integer(2), "Two");
mp.put(new Integer(1), "One");
mp.put(new Integer(3), "Three");
mp.put(new Integer(4), "Four");

Map<Object,String> mp2=new HashMap<Object, String>();
mp2.put(new Integer(2), "Two2");
mp2.put(new Integer(1), "One2");
mp2.put(new Integer(3), "Three2");
mp2.put(new Integer(4), "Four2");

Map<String, Object> mpMaps=new HashMap<String, Object>();

mpMaps.put("Map1",mp);
mpMaps.put("Map2",mp2);

System.out.println("This is a map of Maps: " + mpMaps);

for (int i=0;i<mpMaps.size();i++){
ArrayList<Object> a = new ArrayList<Object>(mpMaps.keySet());
Object o=a.get(i);
System.out.println("all together: " + mpMaps.size() + "each element is: " + o + " value: " + mpMaps.get(o));
}
}
}

关于java - Map of maps - 如何将内部 map 保留为 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4120216/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com