Map存储健值对,根据键得到值,不允许键重复。
1、HashMap、LinkedHashMap、TreeMap 只允许一个键为null,值不限制。
2、Hashtable 线程安全,键不能为null,与HashMap类似,但效率较低,HashMap如果需要实现同步,可以使用Collections.synchronizedMap或ConcurrentHashMap。
3、HashMap键无序;LinkedHashMap键保存了插入的顺序,使用Iterator遍历时,得到的也是插入顺序的记录;TreeMap默认按键的升序排序,可以定制比较器。
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> public class TreeMap<K,V> extends AbstractMap<K,V> implements SortedMap<K,V>, NavigableMap<K,V>, Cloneable, Serializable
public interface SortedMap<K,V> extends Map<K,V>
遍历Map的方法:
Map<String,Integer> hashMap = new HashMap<String,Integer>(); Random random = new Random(); for(int i=1;i<11;i++){ hashMap.put("map"+i, random.nextInt(i)); } Set<String> hashMapKey = hashMap.keySet(); Collection<Integer> hashMapValue = hashMap.values(); Iterator<String> keyVal = hashMapKey.iterator(); System.out.print("key:"); while(keyVal.hasNext()){ System.out.print(" "+keyVal.next()); } Iterator<Integer> hashMapVal = hashMapValue.iterator(); System.out.print("\n value:"); while(hashMapVal.hasNext()){ System.out.print(" "+hashMapVal.next()); }
HashMap、LinkedHashMap、Hashtable和TreeMap区别,布布扣,bubuko.com
HashMap、LinkedHashMap、Hashtable和TreeMap区别
原文:http://www.cnblogs.com/wcj112/p/3580989.html