常用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 | 重量級、線程安全、處理慢 | 不允許 |