1.put方法
put用于向表中添加键值对
public static void main(String[] args) {
HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
hashmap.put(1, "张三");
hashmap.put(2, "李四");
System.out.print(hashmap);
}
输出结果为
{1=张三, 2=李四}
2.get方法
get方法用于获取key对应的value
public static void main(String[] args) {
HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
hashmap.put(1, "张三");
hashmap.put(2, "李四");
System.out.println(hashmap.get(1));
System.out.println(hashmap.get(2));
}
输出结果为
张三
李四
3.remove方法
remove方法用于删除key对应的键值对
public static void main(String[] args) {
HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
hashmap.put(1, "张三");
hashmap.put(2, "李四");
hashmap.remove(1);
System.out.println(hashmap.get(1));
System.out.println(hashmap.get(2));
}
运行结果
null
李四
4.clear方法
clear方法会删除所有键值对
public static void main(String[] args) {
HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
hashmap.put(1, "张三");
hashmap.put(2, "李四");
hashmap.clear();
System.out.println(hashmap.get(1));
System.out.println(hashmap.get(2));
}
运行结果
null
null
5.size方法
size方法用于计算hashmap的大小
public static void main(String[] args) {
HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
hashmap.put(1, "张三");
hashmap.put(2, "李四");
System.out.println(hashmap.size());
}
运行结果
2
6.isEmpty方法
isEmpty方法判断hashmap是否为空,为空返回true,否则返回false
public static void main(String[] args) {
HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
hashmap.put(1, "张三");
hashmap.put(2, "李四");
hashmap.clear();
System.out.println(hashmap.isEmpty());
}
运行结果
true
7. replace方法
replace方法替换 hashMap 中是指定的 key 对应的 value
public static void main(String[] args) {
HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
hashmap.put(1, "张三");
hashmap.put(2, "李四");
System.out.println("替换前:"+hashmap.get(1));
hashmap.replace(1,"老王");
System.out.println("替换后:"+hashmap.get(1));
}
运行结果
替换前:张三
替换后:老王
8.containsKey方法
containsKey方法用于如果此映射包含指定键的映射,则返回 true 。
public static void main(String[] args) {
HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
hashmap.put(1, "张三");
hashmap.put(2, "李四");
System.out.println(hashmap.containsKey(3));
hashmap.put(3, "老王");
System.out.println(hashmap.containsKey(3));
}
运行结果
false
true
9.containsValue方法
containsValue方法如果此映射将一个或多个键映射到指定值,则返回 true 。
public static void main(String[] args) {
HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
hashmap.put(1, "张三");
hashmap.put(2, "李四");
System.out.println(hashmap.containsValue("张三"));
hashmap.remove(1);
System.out.println(hashmap.containsValue("张三"));
}
true
false
10.getOrDefault方法
getOrDefault() 方法获取指定 key 对应对 value,如果找不到 key ,则返回设置的默认值。
public static void main(String[] args) {
HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
hashmap.put(1, "张三");
hashmap.put(2, "李四");
System.out.println(hashmap.getOrDefault(1, "老王"));
System.out.println(hashmap.getOrDefault(3, "老王"));
}
运行结果
张三
老王