0

我一直在尝试序列化这个可迭代的 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.
}
4

1 回答 1

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 类不必是可序列化的,因为 Bagged 类不包含对它的引用。请注意,如果包中的对象不可序列化,您也会收到此异常。要强制执行,您需要按如下方式声明 Bagged:

public class Bagged <Item extends Serializable> implements Iterable <Item>, Serializable
于 2013-11-06T10:52:13.993 回答