我一直在尝试序列化这个可迭代的java类以供后续部署。 在下面的类中包含 Serializable 标记会导致java错误。该代码是一个通用的多集(包)实现,它使用链表数据结构并实现迭代器实用程序,以便在多集中轻松进行通用项迭代。 任何人都可以撒上一些编码精灵灰尘并保存情况?帮助Java-beans制作一个典型的文档!!
/**my iterable class **
**/
public class Bagged<Item> implements Iterable<Item> {
private int n;
private Node first;
//create empty bag
public Bagged(){ first= null; n= 0; }
//check if bag is empty
public boolean empty(){return first==null;}
//add item
public void add(Item item){
Node theold = first;
first = new Node();
first.item= item;
first.nextnode = theold;
n++;
}
//return the number of items
public int size(){return n;}
//create linked list class as a helper
private class Node{private Item item; private Node nextnode; }
//returns an iterator that iterates over all items in thine bag
public Iterator<Item> iterator(){
return new ListIterator();
}
//iterator class--> remove() function ommited typical of a bag implementation.
private class ListIterator implements Iterator<Item>
{
private Node current = first;
public void remove(){ throw new UnsupportedOperationException();}
public boolean hasNext(){return current!=null;}
public Item next()
{
if(!hasNext())throw new NoSuchElementException();
Item item = current.item;
current = current.nextnode;
return item;
}
}
//main class omitted- end of iterable class.
}
答案 0 :(得分:1)
发布确切的错误,但如果您只制作了Bagged Serializable,则错误非常明确:
public static void main(String[] args) throws IOException {
Bagged<Object> bag = new Bagged<Object>();
bag.add(new Object());
new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(bag);
}
Exception in thread "main" java.io.NotSerializableException: Bagged$Node
ListIterator类不必是Serializable,因为Bagged类不包含对它的引用。请注意,如果包中的对象不是Serializable,您也会收到此异常。要强制执行,您需要按如下方式声明Bagged:
public class Bagged <Item extends Serializable> implements Iterable <Item>, Serializable