Java-如何打印字典值

Java-如何打印字典值,java,dictionary,Java,Dictionary,我正在尝试创建一个字典,它看起来像。 但是,每当它不允许我获取数组的元素时。我做错了吗 Dictionary zones = new Hashtable(); String[] countries = {"country1", "country2"}; zones.put("Red", countries); System.out.println(zones.get("Red")[0]); 我猜我不能使用数组作为字

我正在尝试创建一个字典,它看起来像。 但是,每当它不允许我获取数组的元素时。我做错了吗

Dictionary zones = new Hashtable();
String[] countries = {"country1", "country2"};
zones.put("Red", countries);
System.out.println(zones.get("Red")[0]);

我猜我不能使用数组作为字典值?是否有替代方法?

使用泛型或类型转换。 这是使用泛型:

Dictionary<String, String[]> zones = new Hashtable<>();
String[] countries = {"country1", "country2"};
zones.put("Red", countries);
System.out.println(zones.get("Red")[0]);

Dictionary上的
get
方法返回
对象
,因此必须将其强制转换为
String[]
。若您使用泛型,那个么编译器将为您处理这个问题,您不必编写类型转换。

什么是字典类?@BeshambherChaukhwan Hashtable扩展了字典类
Dictionary类是任何类的抽象父类,比如Hashtable,它将键映射到值。
Ahhh所以它就像一个
Map
hmm,我不知道这一点。感谢
字典
哈希表
都是遗留的。您会发现Java中包含了更好的替代方案。阅读他们的Javadoc以获得指导。
Dictionary zones = new Hashtable();
String[] countries = {"country1", "country2"};
zones.put("Red", countries);
System.out.println(((String[])zones.get("Red"))[0]);