Jeremy Johnson
Jeremy Johnson

Reputation: 469

Syntax of Serializing a LinkedList<Object>

As an exercise, I am creating a list of Books as a LinkedList and using the Comparator interface to sort them by author or title. First, I create a class of books and ensure that it will print to screen the way I want it to:

class Book {
    String title;
    String author;
    public Book(String t, String a){
        title = t;
        author = a;
    }
    public String toString(){
        return title + "\t" + author;
    }
}

Next, I created a LinkedList that takes Object Book:

LinkedList<Book> bookList = new LinkedList<>();

A class that implements Comparator is created that sorts according to title/author and displays them on a JTextArea inside of my main frame. All of that is working just fine, but there's one glaring bug...I cannot save the file!

I've tried a class that implements Serializable that takes the LinkedList as a argument and then writes a .obj file. When I load it, it fails. It creates the file, but I usually get a NotSerializableException. I also tried saving the file as .ser as I was told that this could make it easier to save it, but this failed on loading, as well.

Does anyone know a good method for serializing a LinkedList using a BufferedReader? Or is there another approach to this? Thank you in advance for your time reading through this question, and also thank you for any advice, comments, or answers that you can provide. Thanks, guys.

Addition: This is the entire code:

import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;

public class Check {

    BookCompare bc = new BookCompare();
    LinkedList<Book> bookList = new LinkedList<>();
    JFrame frame;
    JPanel northPanel, centerPanel, southPanel;
    JButton addBook, saveBook, loadBook;
    JTextField authorField, titleField;
    JTextArea displayBook;

    public static void main(String[] args) {
        new Check().buildGui();
    }

    private void buildGui() {
        frame = new JFrame("Book List");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        northPanel = new JPanel();
        centerPanel = new JPanel();
        southPanel = new JPanel();

        addBook = new JButton("Add Book");
        addBook.addActionListener(new AddButton());
        saveBook = new JButton("Save List");
        saveBook.addActionListener(new SaveButton());
        loadBook = new JButton("Load List");
        loadBook.addActionListener(new LoadButton());

        JLabel authorL = new JLabel("Author:");
        authorField = new JTextField(10);
        JLabel titleL = new JLabel("Title:");
        titleField = new JTextField(10);

        displayBook = new JTextArea(20,40);
        displayBook.setEditable(false);
        JScrollPane scroll = new JScrollPane(displayBook);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        northPanel.add(titleL);
        northPanel.add(titleField);
        northPanel.add(authorL);
        northPanel.add(authorField);
        centerPanel.add(scroll);
        southPanel.add(addBook);
        southPanel.add(saveBook);
        southPanel.add(loadBook);

        frame.getContentPane().add(BorderLayout.NORTH,northPanel);
        frame.getContentPane().add(BorderLayout.CENTER,centerPanel);
        frame.getContentPane().add(BorderLayout.SOUTH,southPanel);

        frame.setVisible(true);
        frame.setSize(500, 500);
        frame.setResizable(false);
        frame.setLocation(375, 50);
    }

    class AddButton implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            addToList();
            sortAndDisplay();
            readyNext();
        }
    }

    private void addToList() {
        String newTitle = titleField.getText();
        String newAuthor = authorField.getText();
        bookList.add(new Book(newTitle, newAuthor));
    }

    private void sortAndDisplay() {
        displayBook.setText(null);
        Collections.sort(bookList,bc);
        for(int i = 0; i < bookList.size(); i++){
            displayBook.append(bookList.get(i).toString());
        }
    }

    private void readyNext() {
        authorField.setText(null);
        titleField.setText(null);
        titleField.requestFocus();
    }

    class SaveButton implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream("save.ser"));
                oo.writeObject(bookList);
                oo.close();
            } catch (IOException ioe){}
        }
    }

    class LoadButton implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                ObjectInputStream oi = new ObjectInputStream(new FileInputStream("save.ser"));
                Object booksIn = oi.readObject();
                Book inBook = (Book)booksIn;
                bookList.add(inBook);
                sortAndDisplay();
                oi.close();
            } catch (Exception exc){}
        }
    }

    class BookCompare implements Comparator<Book> {
        public int compare(Book one, Book two) {
            return one.title.compareTo(two.title);
        }
    }

    class Book implements Serializable{
        String title;
        String author;
        public Book(String t, String a) {
            title = t;
            author = a;
        }
        public String toString(){
            return title + "\t" + author + "\n";
        }
    }
}

Upvotes: 1

Views: 7524

Answers (1)

Prabhaker A
Prabhaker A

Reputation: 8473

make your Book class Serializable like this

class Book implements Serializable{
  String title;
  String author;
  public Book(String t, String a){
     title = t;
     author = a;
  }
  public String toString(){
     return title + "\t" + author;
  }
}

The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.So you don't need to implement any method just declaring is enough.
according to java docs

Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.

update to resolve current issue
You have implemented de-serialization process wrongly.This is the correct implementation.Try this you will get desired result.

class LoadButton implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        try {
            ObjectInputStream oi = new ObjectInputStream(new FileInputStream("save.ser"));
            Object booksIn = oi.readObject();
            bookList = (LinkedList<Book>)booksIn;
            sortAndDisplay();
            oi.close();
        } catch (Exception exc){}
    }
 }

Upvotes: 4

Related Questions