HashTable和Vector为什么逐渐被废弃

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

HashTable,不允许键值为null,还一个就是put方法使用sychronized方法进行线程同步,单线程无需同步,多线程可用concurren包的类型。 如编程思想里面说的作为工具类,封闭性做的不好没有一个方法变量是final的,作为java1.0/1.1时代的容器逐渐被HashMap取代。同样Vector也有同样的问题,作为普通集合类,添加数据的方法也是做了同步,效率受极大影响。

HashTable源码中的put,键和值都不允许为null 
   /**
     * Maps the specified key to the specified
     * value in this hashtable. Neither the key nor the
     * value can be null. 

* * The value can be retrieved by calling the get method * with a key that is equal to the original key. * * @param key the hashtable key * @param value the value * @return the previous value of the specified key in this hashtable, * or null if it did not have one * @exception NullPointerException if the key or value is * null * @see Object#equals(Object) * @see #get(Object) */ public synchronized V put(K key, V value) { // Make sure the value is not null,值为null报空指针 if (value == null) { throw new NullPointerException(); } // Makes sure the key is not already in the hashtable. Entry tab[] = table; int hash = key.hashCode();//key为null,无法计算hashcode也会报空指针 int index = (hash & 0x7FFFFFFF) % tab.length; @SuppressWarnings("unchecked") Entry entry = (Entry)tab[index]; for(; entry != null ; entry = entry.next) { if ((entry.hash == hash) && entry.key.equals(key)) { V old = entry.value; entry.value = value; return old; } } addEntry(hash, key, value, index); return null; }

 

 

转载于:https://my.oschina.net/u/1271447/blog/2988285

你可能感兴趣的:(HashTable和Vector为什么逐渐被废弃)