HashMap 和 HashTable

本文详细介绍了Java中五种Map实现:HashMap、HashTable、ConcurrentHashMap、LinkedHashMap和TreeMap的特点及使用场景。同时提供了Map的基本遍历方法,并附带了一个简单的Map实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

map  


1. HashMap 和 HashTable 和 ConcurrentHashMap  和  LinkedHashMap  和 TreeMap


1)hashMap可以空键空值, 基于hash算法
2)hashTable不允许空键, 基于线程安全(利用synchronized进行方法同步)
3)ConcurrentHashMap不允许有空键, 同样为线程安全(基于对象锁,同样为线程同步,有hash算列表进行线程隔离)
4)LinkedHashMap与hashMap类似, 但是基于链表形式存储, key为有序集合
5)TreeMap为有序map,非线程安全, 基于二叉树




2. Map遍历方式


1) 迭代器遍历


1-1:
Map<String, String> map = new HashMap<String, String>();
Set<String> keys = map.keySet();
Iterator<String> it = keys.iterate();
while(it.hashNext()){
String key = it.next();
Sysout(key  +  map.get(key));
}


1-2:
Map<String, String> map = new HashMap<String, String>();
Set<Entry<String, String>> entrys = map.entrySet();


2)foreach遍历


2-1:
Map<String, String> map = new HashMap<String, String>();
Set<String> keys = map.keySet();
for(String key : keys){
Sysout(key  +  map.get(key));
}


2-2:
Map<String, String> map = new HashMap<String, String>();
Set<Entry<String, String>> entrys = map.entrySet();
for(Entry<String, String> entry : entrys){
Sysout(entry.getKey  +  entry.getValue());
}




3.Map的实现方式


(1):简化版


public class MyMap<K, V> {


static class MyEntry<K, V> {
        K key;
        V value;
        
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
    }

private List<MyEntry<K, V>> list = new ArrayList<>();
private Set<MyEntry<K, V>> sets = new HashSet<>();

public void put(K key, V value){
MyEntry<K, V> e = new MyEntry<K, V>();
e.setKey(key);
e.setValue(value);
list.add(e);
sets.add(e);
}


public V get(K key){
for(MyEntry<K, V> e : list){
if(e.getKey().equals(key)){
return e.getValue();
}
}
return null;
}

public Set<MyEntry<K, V>> entrySet(){
return sets;
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

兰韦韦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值