1
我有2個字典,我想在第二個字典中創建一個副本,然後彼此的方式有所不同。以下是我執行的字典的基礎:如何在另一個java中複製字典
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());
}
在爲我想補充的鑰匙,並在第一字典中已存在的值,但我不知道how.Any想法?
通過'dictionary'你的意思'HashMap'? Java沒有'詞典'... – Guy
是的,HashMaps.I'm很抱歉。 –