32.1 Map接口的概述
- 键值存储模式
- collection中的集合称为单列集合,Map中的集合称为双列集合
- 分类:HashMap和LinkedHashMap
32.2 Map常用的方法
V put(K key,V value);
V get(Object key);
V remove(Obejct key);
Set<K> keySet();
- 如果存储的是重复的值,将原来的值覆盖,返回被覆盖之前的值;若存储的不是重复的元素,那么返回null;
public class Seet {
public static void main(String[] args) {
Map<String, Integer> map = new LinkedHashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
map.put("d", 4);
Set<String> set = map.keySet();//class java.util.LinkedHashMap$LinkedKeySet
Iterator<String> it = set.iterator();
while(it.hasNext()){
System.out.println(map.get(it.next()));
}
}
}
32.3 Entry键值对对象
Set<Map.Entry<K,V>> entrySet();
K getKey();
V getValue();
public class Entryy {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<String, AA> map = new HashMap<String, AA>();
map.put("aa", new AA("zzz",12));
map.put("bb", new AA("xxx",19));
map.put("cc", new AA("lll",17));
for(Map.Entry<String, AA> m : map.entrySet()){
System.out.println(m.getKey() + m.getValue());
}
}
}
- 如果键是对象的话,为了保证键的唯一性的话,要重写hashcode和equals方法
32.4 LinkedHashMap
32.5 Hashtable
- 底层特点和HashMap一样,结果都是哈希表
- hashtable是线程安全的,hashmap是线程不安全的,因此hashtable和vector一样,被hashmap取代(jdk1.2开始)
- hashmap允许存储null键值,但是hashtable不能存储null的键值
- 但是hashtable的子类properties仍然是ok;
32.6 静态导入(JDK5)
import static java.lang.System.out
public class Demo {
public static void main() {
out.println(...);
}
}
32.7 方法的可变参数(JDK5)
- 前提:参数的数据类型确定,参数个数任意
- 本质:可变参数就是一个数组
- 注意:可变参数只能有一个
public int method(int...i){
int sum = 0;
for(int a : i){
sum += a;
}
return sum;
}
32.8 Collections类
static sort; //升序
static binarySearch; //二分查找
static synchronizeCollection(Collection<T> c)
static synchronizeList(List<T> list)
static synchronizeMap(Map<T> map)
static synchronizeSet(Set<S> set)
32.9 集合的嵌套
- ArrayList 嵌套 ArrayList
- Map 嵌套 ArrayList
- Map集合的嵌套