我是 Java 初学者。我遇到的问题之一是在不同的类中使用数组列表。 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 以及文件中的加载内容
最佳答案
您应该为您需要的每个类
导入它。但是,如果您非常频繁地使用ArrayList
并且仅使用ArrayList
,那么您可以创建一个类
,例如:
public class MySharedArrayList {
public static ArrayList<> pl;
}
然后你就可以在任何地方导入这个小文件,但我相信我们想太多了。不要过早优化。这个微观问题可能永远不会出现,因此处理它可能会浪费时间。
关于java - 读写对象链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27207870/