1.不是collection 接口的子接口
2.以key和value结构存储,相当于与y=f(x)关系
3.Map与collection区别:
(1)collection是元素独立存储,一个元素的方式存储。
(2)Map中元素成对存在,键与键值
4.最常用的是HashMap与TreeMap。
5.Map中常用方法:
方法 |
作用 |
Put() |
添加元素的方法,对应的key与value |
putAll() |
取两个Map的并集 |
Remove() |
删除key对应的value值 |
Get () |
根据Key获取对应的Value |
Containskey() |
判断容器是否包含指定key |
Set keySet() |
获取Map中的Key储存到Set当中 |
containsValue() |
判断容器中是否包含指定的value |
Set<map.Entry<key,value>,entryset> |
将对应的key与value返回 |
Void clear() |
删除Map中的所有映射 |
以TreeMap为例测试:
import TreeSet.Student;
import TreeSet.StudentComparator;
import TreeSet.Users;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapTest {
public static void main(String[] args) {
//实例化
Map<Users,String> map =new TreeMap<>();
Users u1 =new Users("xiaochen",20);
Users u2 = new Users("haiying",22);
map.put(u1,"xiaochen");
map.put(u2,"haiying");
Set<Users> keys =map.keySet();
for (Users key:keys
) {
System.out.println(key+"-----"+map.get(key));
}
//比较器实现比较规则
Map<Student,String> treeMap =new TreeMap<>(new StudentComparator());
Student s1 =new Student("xiaochen",18);
Student s2 =new Student("hai",20);
treeMap.put(s1,"xiaochen");
treeMap.put(s2,"hai");
Set<Student> keys1 =treeMap.keySet();
for (Student s:keys1
) {
System.out.println(s+treeMap.get(s));
}
}
}