Map-API及详解

时间:2023-03-09 18:09:14
Map-API及详解

常用API

类别 方法
增加 put、putAll
删除 remove、removeAll、clear
查询 get
取值 entrySet、keySet、values
长度 size
判断 contains、containsAll、isEmpty

HashMap

键与值的关系(无序)

package com.jacob.javase.map;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set; /*
* HashMap:
*/
public class hashMapT {
public static void main(String[] args) {
Map h1 = new HashMap();
h1.put(1, "c");
h1.put(0, "b");
h1.put(3, "a"); // 键遍历:
Set key = h1.keySet();
iter(key);
// 值遍历
Collection value = h1.values();
iter(value);
// 键值遍历
iter(key, h1); System.out.println(h1.size());
} public static void iter(Set s) {
Iterator i = s.iterator();
while (i.hasNext()) {
System.out.print(i.next() + " ");
}
System.out.println();
} public static void iter(Collection s) {
Iterator i = s.iterator();
while (i.hasNext()) {
System.out.print(i.next() + " ");
}
System.out.println();
} public static void iter(Set s, Map h) {
Iterator i = s.iterator();
while (i.hasNext()) {
Object temp = i.next();
System.out.print(temp + ":" + h.get(temp) + " ");
}
System.out.println();
}
}

TreeMap

有序

package com.jacob.javase.map;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap; /*
* treeMap:
*/
public class TreeMapT {
public static void main(String[] args) {
Map h1 = new TreeMap();
h1.put(7, "c");
h1.put(0, "b");
h1.put(3, "a");
h1.put(3, "d"); Set s=h1.keySet();
Iterator i = s.iterator();
while (i.hasNext()) {
Object temp=i.next();
System.out.print(temp + ":"+h1.get(temp)+" ");
} }
}

HashMap与Hashtable

类别 特点 (键/值)null值处理
HashMap 轻量级、线程不安全、处理慢 允许
HashTable 重量级、线程安全、处理慢 不允许