一、Set与Map
Set集合的继承体系:
Map集合的继承体系:
从上面的继承关系我们可以看出来,实现Map接口和Set接口的接口名、类名完全相似。
从上一篇博文的分析我们可以知道,Map集合的key具有一个特征:所有的key不能重复,且key之间没有顺序(TreeMap是有顺序的),如果将Map集合的所有key集中起来,那这些key就组成了一个set集合,则map集合提供了keySet()方法返回所有key组成的集合。这样就实现了Map到Set之间的转换。其实也可以实现Set到Map之间的转换。
下面简单实现一下将Set扩展成Map,自定义个一个SimpleEntry类,
代码如下:
package com.crazyit;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
class SimpleEntry<K, V> implements Map.Entry<K, V>, java.io.Serializable {
private final K key;
private V value;
public SimpleEntry(K key, V value) {
this.key = key;
this.value = value;
}
public SimpleEntry(Map.Entry<? extends K, ? extends V> entry) {
this.key = entry.getKey();
this.value = entry.getValue();
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
V oldValue = this.value;
this.value = value;
return oldValue;
}
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o.getClass() == SimpleEntry.class) {
SimpleEntry se = (SimpleEntry) o;
return se.getKey().equals(getKey());
}
return false;
}
public int hashCode() {
return key == null ? 0 : key.hashCode();
}
public String toString() {
return key + "=" + value;
}
}
public class Set2Map<K, V> extends HashSet<SimpleEntry<K, V>> {
public void clear() {
super.clear();
}
public boolean containsKey(K key) {
return super.contains(new SimpleEntry<K, V>(key, null));
}
boolean containsValue(Object value) {
for (SimpleEntry<K, V> se : this) {
if (se.getValue().equals(value)) {
return true;
}
}
return false;
}
public V get(Object key) {
for (SimpleEntry<K, V> se : this) {
if (se.getKey().equals(key)) {
return se.getValue();
}
}
return null;
}
public V put(K key, V value) {
add(new SimpleEntry<K, V>(key, value));
return value;
}
public void putAll(Map<? extends K, ? extends V> m) {
for (K key : m.keySet()) {
add(new SimpleEntry<K, V>(key, m.get(key)));
}
}
public V removeEntry(Object key) {
for (Iterator<SimpleEntry<K, V>> it = this.