`
winhyt
  • 浏览: 107201 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

Hashtable和HashMap

    博客分类:
  • java
阅读更多
   每次看到HashMap和Hashtable感觉很像,但是又不一样,要我说出个因为所以然啦还真的说不出来,索性整理出来,便于以后查阅!
一、HashMap和Hashtable的区别
    1、Hashtable 的方法是同步的,HashMap未经同步,所以在多线程场合要手动同步HashMap。
    2、 Hashtable不允许null值(key和value都不可以),HashMap允许null值(key和value都可以)
    3、Hashtable这个类的命名不遵循Java API 命名规范,第二个单词首字母小写。--也算一个吧
    4、哈希值使用不同,Hashtable直接使用对象的hashcode。代码如下:
           int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
      而HashMap需要重新计算hash值。代码如下:
          int hash = hash(key.hashCode());
         int i = indexFor(hash, table.length);
         indexFor()方法:
                static int indexFor(int h, int length) {
                 return h & (length-1);
              }
二、遍历Hashtable和HashMap
   遍历 Hashtable 有四种方法:
      1、 直接toString() 方法 获取的是 字符串性质的键值对
      2、 通过枚举Enumeration
            //通过枚举实现遍历
    Enumeration em = hashtable.elements();
             while(em.hasMoreElements()){
System.out.println(em.nextElement());
    }
     3、 通过entrySet() 方法返回一个 Set , 然后进行遍历处理
            //通过set 获取 遍历
Iterator it2 = hashtable.entrySet().iterator();
while(it2.hasNext()){
Map.Entry  en = (Map.Entry)it2.next();
System.out.println(en.getKey());
System.out.println(en.getValue());
}
     4、 遍历Hashtable的值:
           Collection coll = hashtable.values();
Iterator it = coll.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
   遍历HashMap的三种方法
       1、 直接toString(),返回的是字符串性质的键值对!
       2、 使用entrySet() 返回一个set,进行遍历
           //通过set 获取 遍历
Iterator it3 = map.entrySet().iterator();
while(it2.hasNext()){
Map.Entry  en = (Map.Entry)it3.next();
System.out.println(en.getKey());
System.out.println(en.getValue());
}
      3、 遍历值
          //获取所有的value 值
Collection coll1 = map.values();
Iterator it1 = coll1.iterator();
while(it1.hasNext()){
System.out.println(it1.next());
         }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics