Map接口:
HashMap实现原理:
代码示例:
private static void hashMap() {
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
// map的遍历方式一(通过遍历Entry遍历键值)
Set<Entry<Integer, String>> entrySet = map.entrySet();
for (Entry<Integer, String> e : entrySet) {
System.out.println(e.getKey() + "->" + e.getValue());
}
// map的遍历方式二(通过遍历键取值)
Set<Integer> keys = map.keySet();
for (Integer i : keys) {
String value = map.get(i);
System.out.println(i + "->" + value);
}
// 只遍历值
Collection<String> values = map.values();
for (String v : values) {
System.out.println(v);
}
// forEach遍历,(遍历键值)
map.forEach((key, value) -> System.out.println(key + "->" + value));
}
/**
* 基于二叉树的红黑树实现
*/
private static void treeMap() {
Map<Integer, String> map = new TreeMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
map.forEach((key, value) -> System.out.println(key + "->" + value));
}
/**
* LinkedHashMap:具有可预知的迭代顺序。此实现与HashMap的不同之处在于,它维护着一个运行于所有条目的双重链接列表。
*/
private static void linkedHashMap() {
Map<Integer, String> map = new LinkedHashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
map.forEach((key, value) -> System.out.println(key + "->" + value));
}
/**
* JDK1.0开始就有
* 基于哈希表实现(数组+链表)
* 默认数组大小为11,负载因子为0.75f
* 扩充方式:原数组<<1(乘2) + 1
* 线程安全,用在多线程访问时
*/
private static void hashtable() {
Map<Integer, String> table = new Hashtable<>();
table.put(1, "One");
table.put(2, "Two");
table.put(3, "Three");
table.forEach((key, value) -> System.out.println(key + "->" + value));
}
原文:https://www.cnblogs.com/zxfei/p/10907581.html