如何在另一个java

时间:2015-12-31 12:09:24

标签: java hashmap

我有2本词典,我想在第二篇中复制第一篇,然后彼此的方式不同。这是我的词典的实现:

public class CollectionDic1<K,Integer>  implements Id<K,Integer> , Serializable{
private K key;
private Integer value;
private Map<K,Integer> dict;

public CollectionDic1(){
    dict = new HashMap<K,Integer>();
}

public void put(K key, Integer value){
    dict.put(key, value);
}
public int getSize(){
    return dict.size();
}
public K getKey(){ return key; }
public Integer getValue(){return value;}
public void remove(K key){
    try{
        if (isEmpty())
            throw new ExceptionRepo();
        else
            dict.remove(key);

    }catch (ExceptionRepo ex){
            System.err.println("Error: Dictionary is empty.");

    }

}

public boolean isEmpty(){
    return dict.isEmpty();      
}

public Integer get(K k){
    return dict.get(k);
}

public boolean containsKey(K k){
    return dict.containsKey(k);     
}

public void update (K k, Integer v){
    dict.put(k, v);
}
public String toString(){
    Set<K> all = dict.keySet();
    Object[] keysA = all.toArray();
    String res = "";
    for (int i=0; i<dict.size();i++){
        Integer v = dict.get(keysA[i]);
        res += keysA[i].toString() + " : " + v.toString() + "\r\n";         
    }
    return res;

}

}

我在这里尝试:

public void execute{
      //prg is unimportant
      Id<Object,Integer> first= prg.getDict();
      Id<Object,Integer> second = new CollectionDic1<Object,Integer>();
      for (int i=0; i<first.getSize(); i++){
          second.put(first.getKey(), first.getValue());
      }

因为我想添加第一本字典中已存在的键和值,但我不知道如何。任何想法?

2 个答案:

答案 0 :(得分:1)

尝试使用Map.Entry功能

for (Map.Entry<String, JButton> entry : first.entrySet())
{
    second.put(entry.getKey(), entry.getValue());
}

Map.Entry会为您提供密钥和值对。

答案 1 :(得分:0)

您可以在Maps课程中公开CollectionDic1条目集。

public Set getEntrySet(){
    return dict.entrySet();
}

然后,在execute方法中迭代该集合中的每个键:

Iterator it = first.getEntrySet().iterator();
while (it.hasNext()) {
    Map.Entry pair = (Map.Entry)it.next();
    second.put(pair.getKey(),pair.getValue());
}