Map是双列集合顶层集合是所有双列集合都可以使用的
Map是接口,不能直接创建对象,可以创建它的实现类的对象;
put方法:添加数据时键不存在则添加,返回null,如果存在则覆盖原有键值对对象,并返回被覆盖的值对象。
remove:返回被删除的值对象,如果不存在返回null;
containsKey,containsValue:判断键或值是否存在;
size:返回集合中键值对的个数;
Map <String,String>map=new HashMap<>();
map.put("mike","jane");
map.put("mke","jne");
map.put("mie","jae");
map.put("mik","jan");
String val=map.put("mike","maarie");
map.remove("mike");
System.out.println(map);
System.out.println(val);
Entry集合就是pair<>对象;java没有tuple;Entry是Map的内部接口;不写Map时要导入Map包;
//1.创建Map集合的对象
Map <Student,String>map=new HashMap<>();
map.put(new Student("zhangsan",23),"江苏");
map.put(new Student("lisi",24),"上海");
map.put(new Student("wangwu",25),"福建");
map.put(new Student("heliu",26),"陕西");
//Map集合的遍历:
// 1。获取键值,根据键值遍历 Set<Student>keys=map.keySet();
//2.获取整个集合的pair对象,进行遍历; Set<Map.Entry<Student,String>>entiries=map.entrySet();
//使用foreach进行遍历;
//单独获取健对象
Set<Student>keys=map.keySet();
for(Student stu:keys)
{
//根据键获得值
String value=map.get(stu);
System.out.println(stu+" = "+value);
}
System.out.println("_____________________________");
//获取pair对象
Set<Map.Entry<Student,String>>entiries=map.entrySet();
for(Map.Entry<Student,String>entry:entiries)
{
System.out.println(entry.getKey()+" = "+entry.getValue());
}
System.out.println("_____________________________");
//使用foreach进行遍历
map.forEach(new BiConsumer<Student, String>() {
@Override
public void accept(Student student, String s) {
System.out.println(student+" = "+s);
}
});
HashMap的键对象如果是自定义对象,就需要重写hashCode方法以及equals方法
LinkedHashMap
增加了双向链表机制,保证遍历顺序与存储顺序一致;
TreeMap
TreeSet,TreeMap的键值如果是自定义对象需要实现Comparabale接口里的comapreTo方法;