Set代表一种集合元素无序,集合元素不可重复的集合,Map则代表一种由多个key-value对组成的集合,Map集合类似于传统的关联数组。表面上看它们之间相似性很少,但实际上Map和Set之间有莫大的关联,可以说,Map集合是Set集合的扩展。
Map集合的key具有一个特征:所有key不能重复,key之间没有顺序。也就是说,如果将Map集合的所有key集中起来,那这些key就组成了一个Set集合。Map集合的所有key将具有Set集合的特征,只要把Map的所有key集中起来看,那它就是一个Map,这实现了从Map到Set的转换。
下面程序示范了如何将一个Set集合扩展成Map集合:
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
class SimpleEntry<K,V> implements Map.Entry<K,V>,java.io.Serializable{
privatefinal 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();
}
@Override
public K getKey() {
// TODO Auto-generated method stub
returnkey;
}
@Override
public V getValue() {
// TODO Auto-generated method stub
returnvalue;
}
@Override
public V setValue(V value) {
// TODO Auto-generated method stub
V oldValue = this.value;
this.value = value;
returnthis.value;
}
publicboolean equals(Object o){
if (o == this){
returntrue;
}
if (o.getClass() == SimpleEntry.class){
SimpleEntry se = (SimpleEntry)o;
return se.getKey().equals(getKey());
}
returnfalse;
}
publicint hashCode(){
returnkey == null?0:key.hashCode();
}
public String toString(){
returnkey+"="+value;
}
}
publicclass Set2Map<K,V> extends HashSet<SimpleEntry<K,V>>{
publicvoid clear(){
super.clear();
}
publicboolean containsKey(K key){
returnsuper.contains(new SimpleEntry<K,V>(key,null));
}
publicboolean constainsValue(V value){
for(SimpleEntry<K,V> se:this){
if(se.getValue().equals(value)){
returntrue;
}
}
returnfalse;
}
public V get(Object key){
for(SimpleEntry<K,V> se : this){
if(se.getKey().equals(key)){
return se.getValue();
}
}
returnnull;
}
public V put(K key,V value){
add(new SimpleEntry<K,V>(key,value));
return value;
}
publicvoid 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.iterator(); it.hasNext();){
SimpleEntry<K,V> en = (SimpleEntry<K,V>)it.next();
if(en.getKey().equals(key)){
V v = en.getValue();
it.remove();
return v;
}
}
returnnull;
}
publicint size(){
returnsuper.size();
}
}
publicclass Set2MapTest {
publicstaticvoid main(String[] args){
Set2Map<String,Integer> scores = new Set2Map<String,Integer>();
scores.put("1", 89);
scores.put("2", 90);
scores.put("3", 100);
System.out.println(scores);
System.out.println(scores.size());
scores.removeEntry("1");
System.out.println(scores);
System.out.println(scores.containsKey("2"));
scores.clear();
System.out.println(scores);
}
}
Output:
[3=100, 2=90, 1=89]
3
[3=100, 2=90]
true
[]