Hashtable和HashMap

每次看到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
[color=red]遍历 Hashtable 有四种方法:[/color]
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());
}
[color=red]遍历HashMap的三种方法[/color]:
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());
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值