简体   繁体   English

Java利用ArrayList通过GUI将联系人(对象)写入和读取到文件

[英]Java utilizing ArrayList to write and read contacts(object) to file with GUI

I'm writing a pretty simple program GUI program that emulates a cell phone. 我正在编写一个非常简单的程序GUI程序来模拟手机。 The "cell phone" has four main buttons: phone, contacts, message, and apps. “手机”有四个主要按钮:电话,联系人,消息和应用程序。 I've coded all the GUI and hit a snag while working on the Contact class, which is the backbone of the entire program! 我编写了所有的GUI并在使用Contact类时遇到了麻烦,这是整个程序的支柱!

The Contact class is very straightforward, it has two instance variables of type String which are 'name' and 'number'. Contact类非常简单,它有两个String类型的实例变量,分别是'name'和'number'。 I want to build an ArrayList of type Contact, allow for contacts to be added, and then create methods to append to and read in from a serialized file. 我想构建一个类型为Contact的ArrayList,允许添加联系人,然后创建附加到序列化文件和从序列化文件读入的方法。

At this point I'm very stuck on how to create methods to add objects to the arrayList, and then create methods to append to and read in from a serialized file. 此时我非常关注如何创建将对象添加到arrayList的方法,然后创建要附加到序列化文件并从序列化文件读入的方法。

Here is the Contact class: 这是Contact类:

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 );
   }
}
}

Thanks for the quick responses. 感谢您的快速回复。 I've corrected the equals method and moved the ArrayList to it's own class. 我已经更正了equals方法并将ArrayList移动​​到它自己的类中。 I also cleared up the error on the read method (Java 7 issue). 我还清除了read方法的错误(Java 7问题)。 The current issue I'm running into is on these lines: 我遇到的当前问题是这些问题:

out.writeObject(contact);

and

Contact contact = (Contact)in.readObject();

Since I'm trying to write to and read from an ArrayList, shouldn't the methods reflect that? 因为我正在尝试写入和读取ArrayList,所以方法不应该反映出来吗?

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();
    }
}
}

Appending to the list is as easy as list.add(contact) . 附加到列表就像list.add(contact)一样简单。

Writing to serialization: 写入序列化:

try {
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
    out.writeObject(contact);
} catch(IOException e) {
    e.printStackTrace();
}

Reading: 读:

try {
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
    Contact contact = (Contact)in.readObject();
} catch(IOException | ClassNotFoundException e ) {
    e.printStackTrace();
}

I am afraid that I really understand what you are trying to achieve but I can see two problems in your code: 我担心我真的明白你想要实现的目标,但我可以在你的代码中看到两个问题:

  1. You have created your Contact class with static attributes, which means all the objects will share the same value of name & number. 您已使用静态属性创建了Contact类,这意味着所有对象将共享相同的name和number值。 It seems to be problematic and i will advice you to create non-static attributes when there seems to be no need to share them. 它似乎有问题,我会建议你在似乎不需要共享它们时创建非静态属性。

public static String name, number; public static String name,number;

Second problem in your class is that you have put the arraylist of contacts also in it. 你班上的第二个问题是你已经将联系人的arraylist放在其中。 And you have made the class seriablizable. 而你已经使这个班级可以连接。 It means everytime you serialize your contact object, your arraylist will also be serialized along with it, which i assume is not desired. 这意味着每次序列化您的联系对象时,您的arraylist也会与它一起序列化,我认为这是不可取的。 You should create another class and name it such as ContactsCollection and simply create a Arraylist in it, you may chose to have a static arraylist here. 您应该创建另一个类并将其命名为ContactsCollection,并在其中创建一个Arraylist,您可以选择在此处使用静态arraylist。

In your GUI, if you are creating and object, then create an instance of Contact. 在GUI中,如果要创建和对象,则创建Contact实例。 And then simply add it your ContactsCollection.contactList(). 然后简单地将它添加到ContactsCollection.contactList()中。 You may add methods to serialize also in your ContactsColleciton class. 您可以在ContactsColleciton类中添加序列化方法。 You may chose to have a single method in ContactsCollection with argument as Contact object. 您可以选择在ContactsCollection中使用单个方法,并将参数作为Contact对象。 First you add the object in the list and then serialize it. 首先,在列表中添加对象,然后对其进行序列化。

It would be too long to post as a comment, hence I post this as an answer.Apart from the already answered points, I want to add a few of my observations here. 发表评论太长了,因此我将其作为答案发布。除了已经回答的观点之外,我想在这里补充几点观察。

There are certain mistakes(if they are unintended) in your code: 您的代码中存在某些错误(如果它们是无意的):

You are declaring name and number both as static . 您将namenumber声明为static What it does is that all the instances of your class Contact will share the same name and number . 它的作用是,您的班级Contact所有实例将共享相同的namenumber I presume all the contacts having same name and number is something very unheard and unintended. 我认为所有具有相同namenumber的联系人都是非常闻所未闻的。

public static String name, number;

So correct it to 所以纠正它

public String name, number;

Though it's more of a warning, but you should provide a serialVersionUID to your Serializable class . 虽然它更像是一个警告,但你应该为Serializable类提供serialVersionUID The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded . 序列化运行时将每个可序列化类与版本号相关联,称为serialVersionUID,在反序列化期间使用该版本号来验证序列化对象的发送方和接收方是否已加载

public static final long serialVersionUID = 42L;

Your definition of equals() will create issues.You are using == to check the equality of two String which in turn will only check for equal references. 你对equals()的定义会产生问题。你正在使用==检查两个String的相等性,而这只会检查相同的引用。 Better approach would be to use the overridden equals() of String which compares the contents. 更好的方法是使用比较内容的String的重写equals()

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

Once you override the equals() for the Contact class, override its hashCode() as well. 一旦覆盖Contact类的equals() ,也要覆盖它的hashCode()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM