Map接口常用的实现类有HashMap和TreeMap。
HashMap类是基于哈希表的Map接口的实现,此实现提供所有可选的映射操作,并允许使用null值和null键,但必须保证键的唯一性。HashMap通过哈希表对其内部的映射关系进行快速查找。此类不保证映射的顺序。
TreeMap类不仅实现了Map接口,还是先了java.util.SortedMap接口。因此,集合中的映射关系具有一定顺序。但在添加、删除和定位映射关系时,就要比HahMap类的性能稍差。由于TreeMap类实现的Map集合中的映射关系是根据键对象按照一定的顺序排列的,因此不允许键对象是null。
import com.tmac.Map.jiekou.Stu;
import java.util.*;
public class MapTest {
public static void main(String[] args) {
// 1 . 由HashMap实现的Map对象。
Map<String,String> map = new HashMap<>();
// 2 . 创建添加对象。
Stu stu1 = new Stu("351","张三");
Stu stu2 = new Stu("512","李四");
Stu stu3 = new Stu("853","王一");
Stu stu4 = new Stu("125","赵六");
Stu stu5 = new Stu("341","黄七");
// 3 . 向集合里添加对象。
map.put(stu4.getId(),stu4.getName());
map.put(stu5.getId(),stu5.getName());
map.put(stu1.getId(),stu1.getName());
map.put(stu2.getId(),stu2.getName());
map.put(stu3.getId(),stu3.getName());
// 4 . 获取Map集合中的Key对象集合。
Set<String> set = map.keySet();
// 5 . 创建集合迭代器。
Iterator<String> it = set.iterator();
// 6 . 遍历Map集合。
System.out.println("HashMap类实现的Map集合,无序:");
while (it.hasNext()){
String str = (String) it.next();
/*
* get(Object key)-----如果存在指定的key对象,则返回该对象对应的值,否则返回null。
*/
String name = (String) map.get(str);
System.out.println(str + " " + name);
}
// 7 . 由TreeMap实现的集合对象。
TreeMap<String,String> treemap = new TreeMap<>();
// 8 . 向集合里添加对象。
treemap.putAll(map);
/*
keySet()-----返回该集合中的所有key对象形成的Set集合。
*/
Iterator<String> iter = treemap.keySet().iterator();
// 9 . 遍历TreeMap集合。
System.out.println("TreeMap类实现的Map集合,键对象升序:");
while(iter.hasNext()){
// 10 . 获取集合中的所有key对象。
String str = (String) iter.next();
/*
11 . 获取集合中的所有velues值。
get(Object key)-----如果存在指定的key对象,则返回该对象对应的值,否则返回null。
*/
String name = (String) treemap.get(str);
System.out.println(str + " " + name);
}
}
}