我正在编写一个非常简单的 GUI 程序来模拟手机。 “手机”有四个主要按钮:电话、联系人、消息和应用程序。我已经编写了所有 GUI 的代码,但在处理 Contact 类(整个程序的支柱)时遇到了障碍!
Contact类非常简单,它有两个String类型的实例变量,分别是“name”和“number”。我想构建一个 Contact 类型的 ArrayList,允许添加联系人,然后创建附加到序列化文件并从中读取的方法。
此时,我非常困惑如何创建方法来将对象添加到 arrayList,然后创建方法来附加到序列化文件并从序列化文件中读取。
这是联系人类:
public class Contact
{
public String name, number;
Contact()
{}
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 );
}
}
}
感谢您的快速回复。我已经更正了 equals 方法并将 ArrayList 移动到它自己的类中。我还清除了 read 方法上的错误(Java 7 问题)。我当前遇到的问题是这样的:
out.writeObject(contact);
和
Contact contact = (Contact)in.readObject();
由于我正在尝试写入和读取 ArrayList,这些方法不应该反射(reflect)这一点吗?
import java.util.*;
import java.io.*;
class ContactsCollection implements Serializable
{
public static final long serialVersionUID = 42L;
ArrayList <Contact> contactList = new ArrayList<Contact>();
public void write()
{
try
{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("contactList.dat"));
out.writeObject(contact);
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void read()
{
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("contactList.dat"));
Contact contact = (Contact)in.readObject();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
最佳答案
添加到列表就像 list.add(contact)
一样简单。
写入序列化:
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(contact);
} catch(IOException e) {
e.printStackTrace();
}
阅读:
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
Contact contact = (Contact)in.readObject();
} catch(IOException | ClassNotFoundException e ) {
e.printStackTrace();
}
关于Java 利用 ArrayList 通过 GUI 将联系人(对象)写入和读取到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16535976/