提到hashtable,先要澄清两个问题hashCode与equals().Hashtable有容量和加载因子,容量相当于桶,因子相当于桶里的对象.而hashCode我们可以把它理解为桶的序号,所以HashCode相同的,即它们在同一个桶里,这两上对象就在同一个桶里,这时候如果他们还equals()的话,那么这两个对象就是一样的.而如果他们的hashCode不一样,即他们不在同一个桶里,那么这两个对象肯定是不一样的.

所以我们在用hashtable进行存储对象时要重写他们的hashCode与equals(),否则会出现很多重复的对象.

hashtable与hashMap最大的区别是,hashtable是方法同步的,而后者是异步的.

先来看看下面的例子吧:

  1. public class Ball {
  2. private int size;
  3. private String name;
  4. public Ball(int size, String name) {
  5. this.size = size;
  6. this.name = name;
  7. }
  8. public void setSize(int size) {
  9. this.size = size;
  10. }
  11. public int getSize() {
  12. return size;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. public String getName() {
  18. return name;
  19. }
  20. public static void main(String[] args) {
  21. Hashtable<Ball, String> hash = new Hashtable<Ball, String>();
  22. , "one"), "1");
  23. , "two"), "2");
  24. , "one"), "1");
  25. System.out.println(hash.size());
  26. }
  27. }

可能有的人会认为打印出出来的结果当然是2,有一个是重复的

但结果是3.

因为默认它们都是用Object对象来实现比较的,所以它们的hashCode当然是不一样的

我们可以加以下代码检查是否是这样

  1. @Override
  2. public int hashCode() {
  3. System.out.println(super.hashCode());
  4. return super.hashCode();
  5. }

那么,如何才能去掉重复的对象的

这里我们必须重写hashCode,如下,我们可以把size相同的对象放入同一个桶里,再比较他们的name

把hashCode方法改为

  1. @Override
  2. public int hashCode() {
  3. System.out.println(size);
  4. return size;
  5. }
  6. 写equals();
  1. <pre class="java" name="code">    @Override
  2. public boolean equals(Object obj) {
  3. if (obj instanceof Ball) {
  4. Ball ball = (Ball) obj;
  5. return name.equals(ball.getName());
  6. }
  7. return false;
  8. }</pre>

再试试,结果就是为2.

hashtable再每添加一个对象的都会先判断他们的hashCode是否一样,如果一样再判断他们是否equals(),如果返回为true的话,那么这个对象将不添加

我们也可以看一下源代码实现

  1. /**
  2. * Maps the specified <code>key</code> to the specified
  3. * <code>value</code> in this hashtable. Neither the key nor the
  4. * value can be <code>null</code>. <p>
  5. *
  6. * The value can be retrieved by calling the <code>get</code> method
  7. * with a key that is equal to the original key.
  8. *
  9. * @param      key     the hashtable key
  10. * @param      value   the value
  11. * @return     the previous value of the specified key in this hashtable,
  12. *             or <code>null</code> if it did not have one
  13. * @exception  NullPointerException  if the key or value is
  14. *               <code>null</code>
  15. * @see     Object#equals(Object)
  16. * @see     #get(Object)
  17. */
  18. public synchronized V put(K key, V value) {
  19. // Make sure the value is not null
  20. if (value == null) {
  21. throw new NullPointerException();
  22. }
  23. // Makes sure the key is not already in the hashtable.
  24. Entry tab[] = table;
  25. int hash = key.hashCode();
  26. int index = (hash & 0x7FFFFFFF) % tab.length;
  27. for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
  28. if ((e.hash == hash) && e.key.equals(key)) {
  29. V old = e.value;
  30. e.value = value;
  31. return old;//这里如果比较结果相同时就返回原来的值
  32. }
  33. }
  34. modCount++;
  35. if (count >= threshold) {
  36. // Rehash the table if the threshold is exceeded
  37. rehash();
  38. tab = table;
  39. index = (hash & 0x7FFFFFFF) % tab.length;
  40. }
  41. // Creates the new entry.
  42. Entry<K,V> e = tab[index];
  43. tab[index] = new Entry<K,V>(hash, key, value, e);
  44. count++;
  45. return null;
  46. }

hashMap允许键与值为空.其他的和hashtable是一样的.

具体可再参考API...

Hashtable与HashMap区别(2)的更多相关文章

  1. Java中List,ArrayList、Vector,map,HashTable,HashMap区别用法

    Java中List,ArrayList.Vector,map,HashTable,HashMap区别用法 标签: vectorhashmaplistjavaiteratorinteger ArrayL ...

  2. Hashtable和HashMap区别

    Hashtable和HashMap区别 相同点: 实现原理,功能相同,可以互用 主要区别: a.hashtable继承Directionary类,HashMap实现Map接口 b.Hashtable线 ...

  3. 【Java】HashTable和HashMap区别

    ①继承不同 public class Hashtable extends Dictionary implements Map public class HashMap extends Abstract ...

  4. HashTable 和 HashMap 区别

    hashMap去掉了HashTable 的contains方法,但是加上了containsValue()和containsKey()方法. hashTable同步的,而HashMap是非同步的,效率上 ...

  5. HashTable和HashMap的区别详解(转)

    一.HashMap简介 HashMap是基于哈希表实现的,每一个元素是一个key-value对,其内部通过单链表解决冲突问题,容量不足(超过了阀值)时,同样会自动增长. HashMap是非线程安全的, ...

  6. HashTable和HashMap的区别详解

    一.HashMap简介 HashMap是基于哈希表实现的,每一个元素是一个key-value对,其内部通过单链表解决冲突问题,容量不足(超过了阀值)时,同样会自动增长. HashMap是非线程安全的, ...

  7. HashTable、HashMap、HashSet

    1. HashMap 1)  hashmap的数据结构 Hashmap是一个数组和链表的结合体(在数据结构称“链表散列“),如下图示: 当我们往hashmap中put元素的时候,先根据key的hash ...

  8. Hashtable、HashMap

    JDK1.6 API public class Hashtable<K,V>extends Dictionary<K,V>implements Map<K,V>, ...

  9. Hashtable和HashMap类的区别

    Hashtable和HashMap类有三个重要的不同之处.第一个不同主要是历史原因.Hashtable是基于陈旧的Dictionary类的,HashMap是Java 1.2引进的Map接口的一个实现. ...

随机推荐

  1. psp系统需求分析

    软件开发方向“PSP系统”软件需求规约 目录 1 引言... 4 1.1 目的... 4 1.2 文档格式... 4 1.3 预期的读者和阅读建议... 4 1.4 范围... 5 1.5 术语... ...

  2. 谈谈python 中__name__ = '__main__' 的作用

    最近刚刚学习python,看到别人的源代码中经常出现这样一个代码段: if __name__ = '__main__' dosomting() 觉得很晕,不知道这段代码的作用是什么,后来上网查了一些资 ...

  3. c# 代理IP获取通用方法

    调用: ConcurrentQueue<string> proxyIpQueue = new ConcurrentQueue<string>(); Grab_ProxyIp(p ...

  4. Palindromic Number (还是大数)

    A number that will be the same when it is written forwards or backwards is known as a Palindromic Nu ...

  5. OnDrawGizmos函数

    如果你想绘制可被点选的gizmos,执行这个函数. 这允许你在场景中快速选择重要的物体. 注意: OnDrawGizmos使用相对鼠标坐标 using UnityEngine; using Syste ...

  6. SPOJ 4487 Splay 基本操作

    插入操作,删除操作和置换操作都是单点的,所以不需要lazy标记.这个很简单,都是两次RotateTo,一次Splay操作就搞定. 求最大连续字段和的操作和线段树的题目类似,只需要保存最左边的连续最大字 ...

  7. python 新时代

    今天看到有关python的文章,感觉很好奇,学了python很久了,但是还没有真正的用过,只是写一些小程序 看了这篇文章以后真的感觉自己所了解都是皮毛,在此与大家分享: 原文链接:http://www ...

  8. Java 类加载机制 ClassLoader Class.forName 内存管理 垃圾回收GC

    [转载] :http://my.oschina.net/rouchongzi/blog/171046 Java之类加载机制 类加载是Java程序运行的第一步,研究类的加载有助于了解JVM执行过程,并指 ...

  9. 解决MS Azure 不能ping的问题

    PsPing v2.01 PsPing implements Ping functionality, TCP ping, latency and bandwidth measurement. Use ...

  10. [转载]MongoDB设置访问权限、设置用户

    MongoDB已经使用很长一段时间了,基于MongoDB的数据存储也一直没有使用到权限访问(MongoDB默认设置为无权限访问限制),今天特地花了一点时间研究了一下,研究成果如下: 注:研究成果基于W ...