Java ArrayList 空指针异常

标签 java serialization arraylist io nullpointerexception

编辑

我已经清理了字符串相等的 .equals 方法,并将 ContactsCollection 初始化更改为:

public static ArrayList<Contact> contactList = new ArrayList<Contact>();

我还更改了执行操作的方法,希望“显示联系人”能够显示多个联系人。

    if (contactInput.equals("Display contacts"))
    {
        ContactsCollection.read();
        for (int i = 0; i < contactList.size(); i++)
        {
            contact = (Contact)contactList.get(i);
            for (int j =0; j < contactList.size(); j++)
            {
                textArea.append(contact.getName() + "," + contact.getNumber() + "\n");
            }
        }
    }

最终写入 .dat 文件,但不包含通过 GUI 添加的任何数据。

结束编辑

我正在编写一个模拟手机 GUI,它充当非常基本的联系人管理器。还有其他几个不处理 ArrayList 的类,它们按预期工作。

当尝试向文件添加联系人时,我在 ContactsCollection 类的第 13 行收到空指针异常:

for (int i = 0; i < contactList.size(); i++)

以及 Contacts (GUI) 类的第 93 行:

contactList.add(contact);

我有一种感觉,在编写 Contacts 和 ContactsCollection 类时我做错了什么。我希望程序按如下方式运行:用户单击添加联系人并输入信息,该信息成为对象联系人,并添加到 contactList ArrayList 并写入(序列化)到文件“contactList.dat”。当用户单击“显示联系人”时,将读入文件并在 GUI 中显示每个联系人。

我认为我设置 ArrayList 的方式存在几个问题,但我认为我已经非常接近让程序按照我的希望运行了。非常感谢任何帮助!

联系人类别:

import java.util.*;
import java.io.*;

public class Contact implements Serializable
{
public static final long serialVersionUID = 42L;
public String name, number;

Contact()
{
    name = "No name";
    number = "No number";
}

Contact (String theName, String theNumber)
{
    this.name = theName;
    this.number = theNumber;
}

public void setName(String aName)
{
    this.name = aName;
}

public void setNumber(String aNumber)
{
    this.number =aNumber;
}

public String getName()
{
    return name;
}

public String getNumber()
{
    return number;
}

public String toString()
{
    return name + ": " + number;
}

public boolean equals(Contact other)
{
   if (name.equals(other.getName()) && number.equals(other.getNumber()))
   {
      return(true);
   }
   else
   {
      return(false);
   }
}   
}

通讯录集合类

import java.io.*;
import java.util.*;

class ContactsCollection
{
public static ArrayList<Contact> contactList;

public static void write()
{
    try 
    {
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("contactList.dat"));
        for (int i = 0; i < contactList.size(); i++)
        {
            out.writeObject(contactList.get(i));
        }
        out.close();
    } 
    catch(IOException e)
    {
        e.printStackTrace();
    }
}

public static void read()
{
contactList = new ArrayList<Contact>();
try
{
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("contactList.dat"));
    Contact temp;
    while (in.available()!=0)
    {
        temp = (Contact)in.readObject();
        contactList.add(temp);
    }
    in.close();
}
catch(FileNotFoundException e)
{
    e.printStackTrace();
}
catch(IOException e)
{
    e.printStackTrace();
}
catch(ClassNotFoundException e)
{
    e.printStackTrace();
}       

}
}

联系人(GUI)类

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

class Contacts extends JFrame implements ActionListener, WindowListener
{
public static final int WIDTH = 400;
    public static final int HEIGHT = 600;
    public static final int SMALL_WIDTH = 200;
    public static final int SMALL_HEIGHT = 100;

private static final Dimension stdBtn = new Dimension(150, 50);    

    JPanel centerPanel, northPanel, southPanel;
ImageIcon icon;
JLabel picture;
JButton addContact, displayContacts;
JScrollPane scroll;
JTextArea textArea;
Clock clock;
Background background;
Contact contact;
ArrayList<Contact> contactList;


public Contacts()
{
    super("Contacts");
    this.setLayout(new BorderLayout());
    this.setSize(WIDTH, HEIGHT);
    this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    addWindowListener(this);
    this.setLocationRelativeTo(null);

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

    centerPanel.setBackground(Color.BLACK);
    southPanel.setBackground(Color.BLACK);      

    clock = new Clock();
    northPanel.add(clock);

    icon = new ImageIcon("ContactsBackground.jpg");
    picture = new JLabel(icon);
    centerPanel.add(picture);

    textArea = new JTextArea("", 10, 30);
    textArea.setEditable(false);
    JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);    
    centerPanel.add(scroll);    

    JButton displayContacts = new JButton("Display contacts");
    displayContacts.addActionListener(this);
    southPanel.add(displayContacts);

    JButton addContact = new JButton("Add contact");
    addContact.addActionListener(this);
    southPanel.add(addContact);

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

    setResizable(false);        
}

public void actionPerformed(ActionEvent e)
{
    contactList = new ArrayList<Contact>();
    JButton source = (JButton)e.getSource();
    String contactInput = source.getText();

    if (contactInput == "Display contacts")
    {
        ContactsCollection.read();
        for (int i = 0; i < contactList.size(); i++)
        {
            contact = (Contact)contactList.get(i);
            textArea.setText(contact.getName() + "," + contact.getNumber() + "\n");
        }
    }
    if (contactInput == "Add contact")
    {
        String name = JOptionPane.showInputDialog(null, "Enter Name");
        String number = JOptionPane.showInputDialog(null, "Enter Number");
        contact = new Contact(name, number);
        contactList.add(contact);
        ContactsCollection.write();
    }
}

public void windowOpened(WindowEvent e)
{}

public void windowClosing(WindowEvent e)
{
    this.setVisible(false);
    background = new Background();
    background.setVisible(true);        
}

public void windowClosed(WindowEvent e)
{}

public void windowIconified(WindowEvent e)
{}

public void windowDeiconified(WindowEvent e)
{}

public void windowActivated(WindowEvent e)
{}

public void windowDeactivated(WindowEvent e)
{}      
}

最佳答案

改变

public static ArrayList<Contact> contactList;

public static ArrayList<Contact> contactList = new ArrayList<>();

在您的版本中 contactListnull 因为您从未初始化它并且在您尝试调用的 write() 方法中 size() 就可以了。

<小时/>

此外,您的 GUI 类中存在一些严重缺陷(在 actionPerformed() 方法中),请阅读此问题来修复它们:How do I compare strings in Java?

<小时/>

还要记住 textArea.setText(...) 将为 textArea 设置完整的文本,因此因为这是在代码中的循环中,所以 textArea 将仅包含该循环最后一次迭代的输出。就您而言,这只是最后一次联系。

关于Java ArrayList 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16557292/

相关文章:

python - Django:没有这样的表 snippets_snippet

mysql - WordPress 元值(序列化)过滤器

java - 计算文本文件中唯一单词的数量

java - 从数组中排除重复值

java - 使用索引初始化静态最终数组

java - 如何使用 JazzyListView 实现 pullToRefreshListView?

java - 尝试从命令提示符运行 java 文件,出现错误

Java计算MPG错误

c++ - 使用 Qt 进行序列化

java - 方法调用和通配符