java - 如何在另一个java中复制字典

标签 java hashmap

我有两个字典,我想从第一个字典复制到第二个字典,然后彼此的方式不同。这是我的字典实现的广告:

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());
      }

我想添加第一个字典中已经存在的键和值,但我不知道如何添加。有什么想法吗?

最佳答案

尝试使用Map.Entry功能

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

Map.Entry 将为您提供键和值对。

关于java - 如何在另一个java中复制字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34546346/

相关文章:

java - 使用java解析robot.txt并判断一个url是否被允许

java - Maven打包有效pom

java - Java 应用程序的生产级 Cassandra 客户端配置

java - JTextPane 中的 html - 标 checkout 现奇怪的框

clojure - 如何获取 clojure 数组映射来维护 assoc 之后的插入顺序?

Java HashMap 未从键获取值

java - 通过基于索引检索 Hashmap 元素

java - 为什么我在 Java 中遇到 EOF 异常?

java - android获取HashMap数组的值

java - Hashmap put 性能因键而异