簡體   English   中英

如何在實現Iterable的類上實現Serializable

[英]how to implement Serializable on a class that is implementing Iterable

我一直在嘗試序列化此可迭代的Java類,以進行后續部署。 在下面的類中包含Serializable標簽會導致Java錯誤。 該代碼是通用的多集(bag)實現,該實現使用鏈接列表數據結構並實現迭代器實用程序,以便在多集內輕松進行通用項迭代。 任何人都可以撒些編碼小精靈粉並節省情況嗎? 幫助Java Bean制作典型的文檔!!

/**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.
}

發布確切的錯誤,但是如果您僅使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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM