Merge pull request #95 from dscho/compatible-serialization

Java-compatible (de)serialization of TreeMap, ArrayList and Number
This commit is contained in:
Joshua Warner
2013-11-06 09:02:12 -08:00
4 changed files with 150 additions and 15 deletions

View File

@ -10,6 +10,10 @@
package java.util;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ArrayList<T> extends AbstractList<T> implements java.io.Serializable {
private static final int MinimumCapacity = 16;
@ -183,4 +187,23 @@ public class ArrayList<T> extends AbstractList<T> implements java.io.Serializabl
public String toString() {
return Collections.toString(this);
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeInt(array.length);
for (T o : this) {
out.writeObject(o);
}
}
private void readObject(ObjectInputStream in)
throws ClassNotFoundException, IOException
{
in.defaultReadObject();
int capacity = in.readInt();
grow(capacity);
for (int i = 0; i < size; i++) {
array[i] = in.readObject();
}
}
}

View File

@ -10,25 +10,37 @@
package java.util;
public class TreeMap<K,V> implements Map<K,V> {
private TreeSet<MyEntry<K,V>> set;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public TreeMap(final Comparator<K> comparator) {
set = new TreeSet(new Comparator<MyEntry<K,V>>() {
public int compare(MyEntry<K,V> a, MyEntry<K,V> b) {
return comparator.compare(a.key, b.key);
}
});
public class TreeMap<K,V> implements Map<K,V> {
private final Comparator<K> comparator;
private transient TreeSet<MyEntry<K,V>> set;
public TreeMap(Comparator<K> comparator) {
this.comparator = comparator;
initializeSet();
}
public TreeMap() {
this(new Comparator<K>() {
private void initializeSet() {
final Comparator<K> comparator = this.comparator != null ?
this.comparator : new Comparator<K>() {
public int compare(K a, K b) {
return ((Comparable) a).compareTo(b);
}
};
set = new TreeSet(new Comparator<MyEntry<K,V>>() {
public int compare(MyEntry<K,V> a, MyEntry<K,V> b) {
return comparator.compare(a.key, b.key);
}
});
}
public TreeMap() {
this(null);
}
public String toString() {
return Collections.toString(this);
}
@ -224,4 +236,26 @@ public class TreeMap<K,V> implements Map<K,V> {
return new Collections.ValueIterator(set.iterator());
}
}
public final static long serialVersionUID = 0x0cc1f63e2d256ae6l;
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeInt(size());
for (Entry<K, V> entry : entrySet()) {
out.writeObject(entry.getKey());
out.writeObject(entry.getValue());
}
}
private void readObject(ObjectInputStream in) throws IOException {
in.defaultReadObject();
initializeSet();
int size = in.readInt();
for (int i = 0; i < size; i++) try {
put((K) in.readObject(), (V) in.readObject());
} catch (ClassNotFoundException e) {
throw new IOException(e);
}
}
}