为了把Set集合扩展为一个Map集合,我们可以考虑定义一个SimpleEntry类,该类代表一个key-value对。当Set集合中的元素全是SimpleEntry对象的时候,那么它就可以当成Map来使用。 package ListAndS
package ListAndSet; import java.io.Serializable; import java.util.Map; import java.util.Objects; /** * Created by wang on 16-4-23. */ public class SimpleEntry继承HashSet实现一个Mapimplements Map.Entry ,Serializable { private K key; private V value; public SimpleEntry(K key,V value){ this.key = key; this.value = value; } public SimpleEntry(Map.Entry entry){ this.key = entry.getKey(); this.value = entry.getValue(); } @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } public boolean equals(Object object){ if(object == this){ return true; } if(object.getClass() == SimpleEntry.class){ SimpleEntry se = (SimpleEntry) object; return se.getKey().equals(getKey()); } return false; } public int hashCode(){ return key == null?0:key.hashCode(); } @Override public String toString() { return key+"="+value; } }
package ListAndSet; import java.util.HashSet; import java.util.Iterator; import java.util.Map; /** * Created by wang on 16-4-23. */ public class Set2Mapextends HashSet > { @Override public void clear() { super.clear(); } //判断是否包含某个key public boolean containsKey(K key){ return super.contains(new SimpleEntry (key,null)); } //判断是否包含某个value public boolean containsValue(V value){ for(SimpleEntry se :this){ if(se.getValue().equals(value)){ return true; } } return false; } //根据Key取出Value public V get(K key){ for(SimpleEntry se:this){ if(se.getKey().equals(key)){ return se.getValue(); } } return null; } //存放入该Map中 public V put(K key,V value){ add(new SimpleEntry (key,value)); return value; } //存放一个Map的key-value对放入该Map中 public void putAll(Map map){ for(K key:map.keySet()){ add(new SimpleEntry (key,map.get(key))); } } //根据指定key删除指定key-value对 public V removeEntry(K key){ for(Iterator > it = this.iterator();it.hasNext();){ SimpleEntry en = it.next(); if(en.getKey().equals(key)){ V v = en.getValue(); it.remove(); return v; } } return null; } public int size(){ return super.size(); } }