Map
方法一:Map集合的遍历之 键找值
键找值思路:
- 通过map.keySet()方法,获取所有键(key)的集合
- 遍历键的集合,获取到每一个键(key)
- 根据键找值map.get(key)
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("a", "张三");
map.put("b", "李四");
map.put("c", "王五");
map.put("d", "赵六");
// 1.通过map.keySet()方法,获取所有键(key)的集合
Set<String> keySet = map.keySet();
Iterator<String> it = keySet.iterator();
while (it.hasNext()) {
// 2.迭代器遍历键的集合,获取到每一个键(key)
String key = it.next();
// 3.根据 键 找 值 map.get(key);
String value = map.get(key);
System.out.println(key + "的值为:" + value);
}
// 简化如下:
/*Set<String> set = map.keySet();
for (String key : set) {
System.out.println(key + "的值为:" + map.get(key));
}*/
}
方法二:Map集合的遍历之 键值对对象找值
键值对对象找值思路:
- 通过map.entrySet()方法获取键值对对象集合Set<Entry<K,V>>
- 遍历键值对对象获取键(key)和值(value)
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("a", "张三");
map.put("b", "李四");
map.put("c", "王五");
map.put("d", "赵六");
// Map.Entry接口是Map接口内部的接口,在HashMap中有内部类Entry实现了Map.Entry接口
// 1.通过map.entrySet()方法获取键值对 对象集合Set<Entry<,V>
Set<Entry<String, String>> entryset = map.entrySet();
// 2.遍历键值对 对象获取键(key)和值(value)
Iterator<Entry<String, String>> it = entryset.iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + "的值为:" + value);
}
// 简化如下:
/*for (Entry<String, String> en : map.entrySet()) {
System.out.println(en.getKey() + "的值为:" + en.getValue());
}*/
}
HashMap
如何保证键的唯一?
HashMap当键(key)是对象(Student)时,如果对象(Student)没有重写hashCode和equals方法,则不会去重,即键值可能会有重复。如果需要去重,则需要重写对象的hashcode和equals方法。
public static void main(String[] args) {
// LinkedHashMap是HashMap的子类。
//特点:底层是链表,所以可实现怎么存怎么取。
LinkedHashMap<String, String> lhm = new LinkedHashMap<>();
lhm.put("a", "张三");
lhm.put("b", "李四");
lhm.put("c", "王五");
lhm.put("d", "赵六");
for (String key : lhm.keySet()) {
System.out.println(key + "的值为:" + lhm.get(key));
}
}
TreeMap(存键的底层是二叉树):
如何保证键的唯一?
TreeMap底层是二叉树,所以类比TreeSet,保证键唯一有两种方式:
- 对象继承Comparator接口,重写compareTo方法
- 在TreeMap中传入Comparetor对象,重写compareTo方法
HashMap<K,V>与Hashtable<K,V>的区别(面试题)
共同点:
- 底层都是hash算法,都是双列集合。
区别:
- HashMap线程不安全,效率高,JDK1.2版本。
- Hashtable是线程安全的,效率低,JDLK1.0版本。
- Hashtable不可以存储null键和null值。
- HashMap可以存储null键和null值。
转载请注明出处:BestEternity亲笔。