[英]Is it possible to serialize Map.keySet without copying the Set?
眾所周知,Map的KeySet是不可序列化的。 但是在某些情況下,我只想通過電線發送包裝在自定義對象中的Map的KeySet。 因此,我實現了writeObject方法來檢查可序列化的Set。
我現在的問題是,是否可以在不將整個Set復制到新Set中的情況下獲得二進制表示形式? 這對我來說似乎效率很低,因為在這種情況下,我們通常會擁有龐大的地圖(這是我們僅發送鍵而不是整個地圖的原因之一)。
public class Serialize2 implements Serializable {
private static final Class TM_KS_CLASS = new TreeMap<>().keySet().getClass();
private static final Class LM_KS_CLASS = new LinkedHashMap<>().keySet().getClass();
private Set<String> testSet;
public String justSomeOtherFieldToSerialize;
public Serialize2(Set<String> testSet) {
this.testSet = testSet;
}
public Set<String> getTestSet() {
return testSet;
}
private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException {
if (!(testSet instanceof Serializable)) {
if (testSet.getClass().equals(TM_KS_CLASS)) {
testSet = new TreeSet<>(testSet);
} else {
testSet = new HashSet<>(testSet);
}
}
stream.defaultWriteObject();
}
@Override
public String toString() {
return "Serialize2{" +
"testSet=" + testSet +
'}';
}
public static void main(String[] args) {
Map<String, Integer> foo = new HashMap<>();
foo.put("lala", 1);
foo.put("lolo", 2);
foo.put("lulu", 3);
foo.put("lili", 4);
Serialize2 sTest = new Serialize2(foo.keySet());
Serialize2 dsTest = (Serialize2) SerializationUtils.deserialize(SerializationUtils.serialize(sTest));
System.out.println(dsTest);
}
}
是的,一種方法是分別序列化每個對象,而無需復制到新的對象集中,
private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException {
Iterator itr = testSet.iterator();
if (testSet.getClass().equals(TM_KS_CLASS)) {
stream.writeBoolean(true);
} else {
stream.writeBoolean(false);
}
stream.writeInt(testSet.size());
while(itr.hasNext()) {
stream.writeObject(itr.next());
}
stream.writeObject(justSomeOtherFieldToSerialize);
}
您需要具有相應的readObject實現,該實現可以分別讀取每個對象並將其放入一個集中,例如,
private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException {
boolean bTypeofmap = stream.readBoolean(); // Whether its a TreeMap or LinkedhashMap
int size = stream.readInt();
testSet = new java.util.HashSet(size);
for(int i = 0; i < size; i++) {
testSet.add(stream.readObject());
}
justSomeOtherFieldToSerialize = (String) stream.readObject();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.