Search code examples
javadictionaryserializationiotreemap

Reading TreeMap from file (Java)?


For a school assignment, I have to create a program that gives a user options to save a contact to a file and list all contacts in the file using a TreeMap. I wrote code to save contacts in the map to the file and read them from it, but I'm getting an error when trying to compile that reads: "incompatible types: object cannot be converted to ContactInfo" on the statement ContactInfo ci = contact.getValue(); How do I fix this?

The relevant code to add a contact to the map and then write the map to the file:

ContactInfo c = new ContactInfo();

System.out.print( "First name: " );
String fName = s.next();
System.out.print( "Last name: " );
String lName = s.next();
c.setName( fName, lName );

System.out.print( "Phone #: " );
String p = s.next();
c.setPhone( p );

System.out.print( "Email address: " );
String e = s.next();
c.setEmail( e );

contacts.put( lName, c );

try
{
    ObjectOutputStream out = new ObjectOutputStream(
                            new BufferedOutputStream(
                            new FileOutputStream( fileName ) ) );

    out.writeObject( contacts );
}

catch( Exception ex )
{
    System.out.println( "Error saving contact to file." );
}

The relevant code to list all contacts:

try
{
    ObjectInputStream in = new ObjectInputStream(
                            new BufferedInputStream(
                            new FileInputStream( fileName ) ) );

    contacts = (TreeMap< String, ContactInfo >) in.readObject();

    in.close();                 
}

catch( Exception exc )
{
    System.out.println( "Error displaying contacts." );
}

for( Map.Entry contact : contacts.entrySet() )
{
    ContactInfo ci = contact.getValue();
    System.out.println( ci.getName() + "\t" + ci.getPhone() + "\t" + ci.getEmail() );
}

Solution

  • It seems that you are reading and writting your contacts as type 'Object'. Try to cast your value like this:

    ContactInfo ci = (ContactInfo) contact.getValue();
    

    If java tells you you can not cast it, you will have to find another wat to save/load these objects.