序列化 arrayList 中的对象,该对象在程序运行时被修改

问题描述 投票:0回答:0

初学Java,正在学习序列化和反序列化。我制作了一个过期小程序来帮助我学习并掌握它。我正在尝试保存 arrayList 的数据,这样我就不必在每次运行程序时都制作一个没有任何信息的全新数据。

如果我在程序运行时通过添加或删除 arrayList 来修改 arrayList,我是否必须重新序列化整个 arrayList?或者是否有一种方法可以简单地序列化列表中的对象?

如果您需要,这是我的小演示项目:

相框

package deserialization.and.serialization;

import java.util.ArrayList;

/**
 *
 * @author m_che
 */
public class frame extends javax.swing.JFrame {

    /**
     * Creates new form frame
     */
    public frame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        lblJobType = new javax.swing.JLabel();
        lblSalary = new javax.swing.JLabel();
        lblCompany = new javax.swing.JLabel();
        JobTypeTxt = new javax.swing.JTextField();
        salaryTxt = new javax.swing.JTextField();
        companyTxt = new javax.swing.JTextField();
        btnAdd = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        InstructionsTxt = new javax.swing.JTextArea();
        btnSave = new javax.swing.JButton();
        jScrollPane = new javax.swing.JScrollPane();
        jobList = new javax.swing.JList<>();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lblJobType.setText("Job Type:");

        lblSalary.setText("Salary per Hr:");

        lblCompany.setText("Company:");

        JobTypeTxt.setEditable(false);

        salaryTxt.setEditable(false);

        companyTxt.setEditable(false);

        btnAdd.setText("Add Job");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnDelete.setText("Delete Job");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        InstructionsTxt.setEditable(false);
        InstructionsTxt.setColumns(20);
        InstructionsTxt.setLineWrap(true);
        InstructionsTxt.setRows(5);
        InstructionsTxt.setWrapStyleWord(true);
        jScrollPane1.setViewportView(InstructionsTxt);

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        jobList.setModel(new javax.swing.AbstractListModel<String>() {
            public int getSize() { return Data.getJobs().size(); }
            public String getElementAt(int i) { return Data.getJobs().get(i).getCompany(); }
        });
        jobList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane.setViewportView(jobList);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblJobType)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(JobTypeTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblSalary)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(salaryTxt))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnAdd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnDelete))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblCompany)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(companyTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(24, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 288, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(39, 39, 39)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblJobType)
                            .addComponent(JobTypeTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblSalary)
                            .addComponent(salaryTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblCompany)
                            .addComponent(companyTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSave)
                        .addGap(38, 38, 38)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnAdd)
                            .addComponent(btnDelete))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(41, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                       
        JobTypeTxt.setText("");
        salaryTxt.setText("");
        companyTxt.setText("");
        
        JobTypeTxt.setEditable(true);
        salaryTxt.setEditable(true);
        companyTxt.setEditable(true);
        InstructionsTxt.setText("The textfields above have now become editable. Type in your new job's type, salary, and company, and then click save to add it to the list.");
    }                                      

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                          
        if(jobList.getSelectedValue() == null) {
            InstructionsTxt.setText("Make sure you select an object in the list that you want to delete.");
        } else {
            Data.getJobs().remove(jobList.getSelectedIndex());
            
            JobTypeTxt.setText("");
            salaryTxt.setText("");
            companyTxt.setText("");
            jobList.revalidate();
            jobList.repaint();
        } 
    }                                         

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {                                        
        try{
            double salary = Double.parseDouble(salaryTxt.getText().trim());
            
            Job job = new Job(JobTypeTxt.getText().trim(), salary, companyTxt.getText().trim());
            Data.getJobs().add(job);
            
            
            JobTypeTxt.setEditable(false);
            salaryTxt.setEditable(false);
            companyTxt.setEditable(false);
            
            InstructionsTxt.setText("");
        } catch(NumberFormatException e) {
            InstructionsTxt.setText("The salary must be a valid decimal!");
        }
        
        jobList.revalidate();
        jobList.repaint();
    }                                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JTextArea InstructionsTxt;
    private javax.swing.JTextField JobTypeTxt;
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnSave;
    private javax.swing.JTextField companyTxt;
    private javax.swing.JScrollPane jScrollPane;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList<String> jobList;
    private javax.swing.JLabel lblCompany;
    private javax.swing.JLabel lblJobType;
    private javax.swing.JLabel lblSalary;
    private javax.swing.JTextField salaryTxt;
    // End of variables declaration                   
}

课堂作业


package deserialization.and.serialization;


public class Job {
    private String type;
    private double salaryPerHr;
    private String company;
    
    public Job(String type, double salary, String company) {
        this.type = type;
        salaryPerHr = salary;
        this.company = company;
    }
    
    public String getType() {
        return type;
    }
    
    public void setType(String type) {
        this.type = type;
    }
    
    public double getSalary() {
        return salaryPerHr;
    }
    
    public void setSalary(double salary) {
        salaryPerHr = salary;
    }
    
    public String getCompany() {
        return company;
    }
    
    public void setCompany(String company) {
        this.company = company;
    }
}

类数据

package deserialization.and.serialization;

import java.util.ArrayList;

public class Data {
    private static ArrayList<Job> jobs = new ArrayList<Job>();
    
    public static ArrayList<Job> getJobs() {
        return jobs;
    }
    
    public static void setJobs(ArrayList<Job> allJobs) {
        jobs = allJobs;
    }
}

GUI 的外观

GUI

感谢您的任何帮助:)

java serialization netbeans jframe deserialization
© www.soinside.com 2019 - 2024. All rights reserved.