作者qrtt1 (隐者)
看板java
标题Re: [问题] 请问一个关於Map的问题
时间Thu May 25 13:48:58 2006
※ 引述《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