Re: [問題] 請問一個關於Map的問題

看板java作者 (隱者)時間19年前 (2006/05/25 13:48), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
※ 引述《zeebra (Be Bop)》之銘言: : 關於Map以TreeMap為例 : 我的目的是想將TreeMap A的所有內容複製到TreeMap B : 但對於TreeMap有三個方法我有些問題 : 第一個為建構子 : TreeMap(Map m) : Constructs a new map containing the same mappings as the given map, : sorted according to the keys' natural order. : 第二個為putAll方法 : putAll(Map map) : Copies all of the mappings from the specified map to this map. : 以上這兩個方法我試過之後 : 發現他們是複製記憶體的位置 也就是說 使用TreeMap B = new TreeMap(A) : 是複製reference 若使用B.putAll(A)的道的結果似乎也相同 也是複製reference : 有什麼方法是可以複製內容而不是複製reference的呢?? : 另外 TreeMap的clone方法是做什麼用的呢? 1. 實作clonable 2. 用serialization (javaworld.com看到的概念) ================================================================== import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class TestMap { public static void main(String[] args) throws IOException, ClassNotFoundException { Map m = Collections.synchronizedMap(new TreeMap()); m.put("a", new Integer(2)); m.put("b", new Integer(3)); m.put("c", new Integer(4)); PipedOutputStream pos = new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(pos); ObjectOutputStream oos = new ObjectOutputStream(pos); oos.writeObject(m); ObjectInputStream ois = new ObjectInputStream(pis); Map m_clone = (Map)ois.readObject(); Set s = m_clone.keySet(); Iterator it =s.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 163.26.34.248
文章代碼(AID): #14TKKRUb (java)
文章代碼(AID): #14TKKRUb (java)