JAVA集合VI-Map接口
1.Map接口底层结构
虚线+箭头:表示实现接口
实线+箭头:表示继承
2.Map接口特点
(1)特点
- Map与Collection并列存在,用于保存具有映射关系的数据:key-value
- Map中的key和value可以是任何引用类型的数据,会封装到HashMap$Node对象中
- Map中的key不允许重复,原因和HashSet一样,前面分析过
- Map中的value可以重复
- Map的key可以为null,value也可以为null,注意key为null,只能有一个,value为null可以有多个
- 常用String类作为Map的key
- key和value之间存在单项一对一关系,即通过指定的key总能找到对应的 value
(2)key-value的结构示意图
3.Map接口常用方法
(1)Map接口所有方法
(2)简单练习
public class MapTest {
public static void main(String[] args) {
Map map=new HashMap();
map.put("张三",new Book("张三的艺术",100));
map.put("李四",100);
map.put("王五","大傻子");
System.out.println(map);
//根据键删除映射关系:remove(key)
map.remove("张三");
System.out.println(map);
//根据键获取值get(key)
System.out.println(map.get("李四"));
//获取元素个数size()
System.out.println(map.size());
//判断是否为空isEmpty();
System.out.println(map.isEmpty());
//查找键值是否存在containsKey(key)
System.out.println(map.containsKey("李四"));
}
}
class Book{
private String name;
private double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
4.Map接口遍历方式
public class MapTest {
public static void main(String[] args) {
Map map=new HashMap();
map.put("张三",new Book("张三的艺术",100));
map.put("李四",100);
map.put("王五","大傻子");
//遍历方式一:使用entrySet()
Set set = map.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("==============");
//遍历方式二:使用keySet()
Set set1 = map.keySet();
Iterator iterator1 = set1.iterator();
while (iterator1.hasNext()){
Object next = iterator1.next();
System.out.println("key="+next+"value="+map.get(next));
}
//获取values值
Collection values = map.values();
for (Object value : values) {
System.out.println(value);
}
}
}
class Book{
private String name;
private double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}