HashMap
数组和列表将元素存储为有序集合,每个元素都有一个整数索引。
HashMap用于将数据集合存储为键和值对。一个对象被用作另一个对象(值)的键(索引)。
put,remove和get方法用于添加,删除和访问HashMap中的值。
下面是一个例子:
import java.util.HashMap;
public class MyJavaClass {
public static void main(String[] args) {
HashMap<String, Integer> points = new HashMap<String, Integer>();
points.put("Shuter", 90);
points.put("Loen", 85);
points.put("Lu", 80);
System.out.println(points.get("Loen"));
}
}
// 输出 85
我们创建了一个HashMap,其中的字符串作为键,整数作为其值。
提示:使用get方法和相应的键来访问HashMap元素。
一个HashMap不能包含重复的键。使用已存在的键添加新项目会覆盖旧元素。
HashMap类提供了containsKey和containsValue方法,用于确定是否存在指定的键或值。
如果尝试获取映射中不存在的值,则返回null值。
import java.util.HashMap;
public class MyJavaClass {
public static void main(String[] args) {
HashMap<String, Integer> points = new HashMap<String, Integer>();
points.put("Shuter", 90);
System.out.println(points.containsKey("Shuter"));
}
}
运行结果:
true
null
提示:null是表示缺少值的特殊类型。