我是Java的初学者。我遇到的问题之一是在不同的类中使用arraylist。
MainWindow类读取文件到arraylist

public class MainWindow extends javax.swing.JFrame {

ArrayList <Product> pl;
List<Product> list = new ArrayList<>();

boolean test = false;

ObjectOutputStream oos;
ObjectInputStream ois;

private String file ="C://temp//Data.dat";
String number ="";


public MainWindow() {
    initComponents();
    pl = new ArrayList<>();
    try {
        ois = new ObjectInputStream(new FileInputStream(file));
        do{
            list = (ArrayList<Product>) ois.readObject();
            for(int i =0; i < list.size(); i++){
                pl.add(list.get(i));

            }
            for(Product px : pl){
                number = px.getpNumber();
                System.out.println(px);
                System.out.println(number);

            }
            System.out.println(pl);

            //System.out.println(table);
        }

        while(test = false);


    } catch (FileNotFoundException ex) {
        Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("file not founf");
    }
    catch (EOFException ex){
        System.out.println("end of file");
        ex.printStackTrace();
        test = true;
    }

    catch (IOException | ClassNotFoundException ex) {
        Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("class not found");
    }
    finally{
        try {
            ois.close();
        } catch (IOException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
public ArrayList<Product> getProduct(){
    return pl;

private void addPanelActionPerformed(java.awt.event.ActionEvent evt) {
   addPanel ap;
     try {
         ap = new addPanel();
         ap.setVisible(true);
     } catch (ClassNotFoundException ex) {
         Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
     }
}


我想使用相同的Arraylist pl将新产品添加到列表中,而不会覆盖ArrayList。
我不知道如何在不加载每个类的同一个文件的情况下执行此操作,而我需要ArryList和文件中的加载内容

最佳答案

您应该为每个需要的class导入它。但是,如果您经常使用ArrayList并且仅使用ArrayList,则可以创建class,例如:

public class MySharedArrayList {
    public static ArrayList<> pl;
}


然后您可以将这个小文件导入到任何地方,但是我认为我们对此考虑过多。不要过早优化。这个微观问题可能永远不会出现,因此可能会浪费时间来处理它。

07-24 09:46
查看更多