什么类允许我操作索引和值


What class allows me to manipulate the index and value?

在PHP中,我可以改变数组的索引和值。

$array = array("foo" => 54);

然后

$array["foo"] 

返回54。我如何在Java中做到这一点?

与PHP的关联数组等价的是Java中的Map。两者都共享键值对实现,最常用的实现是HashMap

Map<String, Integer> map = new HashMap<>();
map.put("foo", 54);
System.out.println(map.get("foo")); // displays 54

存在其他实现,如LinkedHashMap保留插入顺序,TreeMap根据其键的自然顺序排序。

使用映射实现来完成此操作:

Map<String, Integer> m = new HashMap<String, Integer>();
m.put("foo", 54);
m.get("foo"); // will yield 54