gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:41:53 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com