java试题(HashMap 和 HashTable)
2016-04-06 23:11
459 查看
A. 他们都实现了Map 接口
B. HashMap 非线程安全,在多个线程访问Hashtable时,不需要自己为 它的方法实现同步,而HashMap 就必须为之提供额外同步
C. HashMap允许将null作为一个entry的key或者value,而Hashtable不允许
D. 通过contains方法可以判断一个对象是否存在于HashMap或者Hashtable中
答案:D
解析:
//HashMap的源码
//Hashtable的源码
A.都实现了Map接口 正确
B.这里已put方法为例,其他get,remove 等方法类似
//HashMap的put方法,没有同步
//Hashtable的put方法,使用了synchronized
B. HashMap 非线程安全,在多个线程访问Hashtable时,不需要自己为 它的方法实现同步,而HashMap 就必须为之提供额外同步
C. HashMap允许将null作为一个entry的key或者value,而Hashtable不允许
D. 通过contains方法可以判断一个对象是否存在于HashMap或者Hashtable中
答案:D
解析:
//HashMap的源码
public class HashMap<K,V>extends AbstractMap<K,V>implements Map<K,V>, Cloneable, Serializable { ... }
//Hashtable的源码
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, java.io.Serializable { ... }
A.都实现了Map接口 正确
B.这里已put方法为例,其他get,remove 等方法类似
//HashMap的put方法,没有同步
public V put(K key, V value) { if (key == null) return putForNullKey(value); //C.可以为null int hash = hash(key.hashCode()); int i = indexFor(hash, table.length); for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null; }
//Hashtable的put方法,使用了synchronized
public synchronized V put(K key, V value) { // Make sure the value is not null //C.不可以为null if (value == null) { throw new NullPointerException(); } // Makes sure the key is not already in the hashtable. Entry tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { V old = e.value; e.value = value; return old; } } modCount++; if (count >= threshold) { // Rehash the table if the threshold is exceeded rehash(); tab = table; index = (hash & 0x7FFFFFFF) % tab.length; } // Creates the new entry. Entry<K,V> e = tab[index]; tab[index] = new Entry<K,V>(hash, key, value, e); count++; return null; }
//以下是Hashtable的方法 public synchronized boolean contains(Object value) public synchronized boolean containsKey(Object key) public boolean containsValue(Object value) //以下是HashMap中的方法,注意,没有contains方法,所以,D错误 public boolean containsKey(Object key) public boolean containsValue(Object value)
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树