Map接口和常用方法
Map体系的继承图
Map接口常用方法
- put:添加
- remove:根据健删除映射关系
- get: 根据键获取值
- size:获取元素个数
- isEmpty:判断个数是否为0
- clear:清除
- containsKey:查找键是否存在
import java.util.HashMap;
import java.util.Map;
public class MapMethod {
public static void main(String[] args) {
//map接口常用方法
Map map = new HashMap();
map.put("test1", new Book("", 100));//ok
map.put("test1", "test2");//替换
map.put("test3", "test4");//ok
map.put("test5", "test4");//ok
map.put("test6", null);//ok
map.put(null, "test7");//ok
map.put("test8", "test9");//ok
System.out.println("map = " + map);
//remove:根据健删除映射关系
map.remove(null);
System.out.println("map = " + map);
//get: 根据键获取值
Object test8 = map.get("test8");
System.out.println("test8 = " + test8);
//size:获取元素个数
System.out.println("k-v = " + map.size());
//isEmpty:判断个数是否为0
System.out.println(map.isEmpty());//F
//clear:清除
map.clear();
System.out.println("map = " + map);
//containsKey:查找键是否存在
System.out.println(map.containsKey("wsh"));//F
map.put("wsh", "wsh的老婆");
System.out.println(map.containsKey("wsh"));//T
}
}
class Book {
private String name;
private double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
}