问题的描述:
映射(Maps)的用法
解决方案:
映射这种数据结构含有两个部分:关键字和值。对于每个关键字都有一个值,也就是说,一个关键字映射一个值。映射允许通过关键字访问数据结构。
Java 在Collections API的Map接口中声明了一对一的映射。当向映射中插入一对关键字和值时,如果出现关键字重用,则用新值替换映射中原有的值,不在映射中增加一个元素。
请看下例:
import java.util.Map;
import java.util.HashMap;
public class TestMap {
public static void main(String[] args) {
Map map = new HashMap();
map.put("abc", new Integer(5));
map.put("abd", new Integer(6));
map.put("abf", new Integer(7));
// 会覆盖原来的值7
map.put("abf", new Integer(8));
System.out.println(map.get("abf"));
}
}
编译和运行的结果为:
8
在应用中可以把该容器里关键字单独取出来放到一个实现Set接口的容器里,然后过滤出你所需要的关键字,然后根据这个关键字把对应的值取出来。
import java.util.Map;
import java.util.*;
public class TestMap1 {
public static void main(String[] args) {
Map map = new HashMap();
map.put("abc", new Integer(5));
map.put("abd", new Integer(6));
map.put("abf", new Integer(7));
map.put("abf", new Integer(8));
// 得到关键字的集合
Set s = map.keySet();
Iterator i = s.iterator();
String str = null;
while (i.hasNext()) {
str = (String) i.next();
if (str.equals("abf"))
System.out.println(map.get(str));
}
}
}
结果还是8
注意:这里的关键字对象还是由hashCode()和equals()方法共同决定的