【JavaSE】1つのキーが複数のvalueに対応するHashMap
2175 ワード
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class MultiHashMap<K extends Object, V extends List> extends AbstractMap {
private Map map;
public MultiHashMap() {
map = new HashMap<K, V>();
}
@Override
public Set entrySet() {
return map.entrySet();
}
@Override
public Object put( Object k, Object v ) {
boolean isList = v instanceof List;
if( isList || ( null == v ) ){
return map.put( k, (List) v );
}
return null;
}
public Object put( K k, V v ) {
return map.put( k, v );
}
@Override
public void putAll(Map m ) {
if( m instanceof MultiHashMap ){
Iterator itr = m.entrySet().iterator();
Entry entry = null;
while( itr.hasNext() ){
entry = (Entry) itr.next();
put(entry.getKey(), entry.getValue() );
}
}
}
}
/** */
public class TestMultiHashMap {
public static void main(String[] args) {
MultiHashMap<String, List > multiMap = new MultiHashMap<String, List >();
ArrayList list = new ArrayList();
list.add( 1 );
list.add( 2 );
list.add( 3 );
list.add( 1 );
list.add( null );
multiMap.put( "1", list );
multiMap.put( "2", list );
multiMap.put( null, null );
System.out.println( "multiMapsize=" + multiMap.size() );
MultiHashMap<String, List > multiMap1 = new MultiHashMap<String, List >();
multiMap1.putAll( multiMap );
System.out.println( "multiMap1size=" + multiMap1.size() );
List llll = (List)multiMap1.get("1");
Iterator itr = llll.iterator();
while( itr.hasNext() ){
System.out.println( itr.next() );
}
Set ss = multiMap1.entrySet();
Iterator iterator = ss.iterator();
while(iterator.hasNext()){
Entry<String, List> obj = (Entry<String, List>) iterator.next();
System.out.println(obj.getKey()+"-------"+obj.getValue());
}
}
}