[英]writeObject and readObject method for a Serializable class which extends ArrayList<E>
I want to extend the ArrayList class to create a collection which doesn't hold duplicate element and use array internally to store. 我想扩展ArrayList类以创建一个不包含重复元素的集合,并在内部使用数组进行存储。
SetUniqueList
stores unique element, but I want to add more functionality. SetUniqueList
存储唯一元素,但我想添加更多功能。
I am stuck in the method writeObject
and readObject
. 我陷入方法
writeObject
和readObject
。 This is the implementation in ArrayList
: 这是
ArrayList
的实现:
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{
int expectedModCount = modCount;
s.defaultWriteObject();
s.writeInt(elementData.length);
for (int i=0; i<size; i++)
s.writeObject(elementData[i]);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
int arrayLength = s.readInt();
Object[] a = elementData = new Object[arrayLength];
for (int i=0; i<size; i++)
a[i] = s.readObject();
}
Clearly I cannot access private transient Object[] elementData;
显然,我无法访问
private transient Object[] elementData;
. 。 I am puzzled that should I create class like
ArrayList
, not extending it, or there is any other artcitectural way to do this? 我不知道应该创建像
ArrayList
这样的类,而不扩展它,还是有其他方法来实现?
I need to use subList
so that changes in the sub list are reflected in this list. 我需要使用
subList
以便子列表中的更改反映在此列表中。
I can think of a couple of ways to implement readObject
and writeObject
on a subclass of ArrayList
: 我可以想到几种在
ArrayList
的子类上实现readObject
和writeObject
的方法:
Use reflection to call the private methods in ArrayList
(Nasty!! But possibly justifiable.). 使用反射来调用
ArrayList
的私有方法(讨厌!但是可能是合理的。)。
Use super.iterator()
etctera to iterate the elements in your readObject
method. 使用
super.iterator()
etctera迭代readObject
方法中的元素。
However, I think you would be better off turning your subclass of ArrayList
into a wrapper class that delegates operations to a real ArrayList
. 但是,我认为最好将
ArrayList
的子类转换为将操作委托给实际ArrayList
的包装器类。 Just make sure that the wrapper class is Serializable
and the private variable containing the reference to the wrapped list is not marked as transient
.) 只需确保包装器类可
Serializable
并且包含对包装列表的引用的私有变量未标记为transient
。)
An LinkedHashSet
might be another option ... depending on how the collection is used. LinkedHashSet
可能是另一个选项……取决于集合的使用方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.