I'm writing a pretty simple program GUI program that emulates a cell phone. 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!
The Contact class is very straightforward, it has two instance variables of type String which are 'name' and '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.
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.
Here is the Contact class:
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. I also cleared up the error on the read method (Java 7 issue). 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?
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();
}
}
}