Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures - Retired Organizing Data Serialization

Joel Wood
Joel Wood
6,327 Points

Treets - ClassCastException Error

I receive the following compiler error when running the code (code posted separately). Please advise, and thanks for the help:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to [Lcom.teamtreehouse.Treet;
at com.teamtreehouse.Treets.load(Treets.java:25)
at Example.main(Example.java:34)

Joel Wood
Joel Wood
6,327 Points
import java.util.Arrays;
import java.util.Date;

import com.teamtreehouse.Treet;
import com.teamtreehouse.Treets;

public class Example{

  public static void main(String[] args){
//    Treet treet = new Treet(
//      "craigsdennis",
//      "Want to be famous? Simply tweet about Java and use " +
//        "the hashtag #treet. I'll use your tweet in a new " +
//        "@treehouse course about data structures.",
//      new Date(1421849732000L)
//    );
//    Treet secondTreet = new Treet(
//      "journeytocode",
//      "@treehouse makes learning Java sooooo fun! #treet",
//      new Date(1421878767000L)
//    );
//    System.out.printf("This is a new Treet: %s %n", treet);
//    System.out.println("The words are:");
//    for (String word : treet.getWords()){
//      System.out.println(word);
//    }
//    
//    Treet[] treets = {treet, secondTreet};
//    Arrays.sort(treets);
//    for(Treet exampleTreet : treets){
//      System.out.println(exampleTreet);
//    }
//    Treets.save(treets);
    Treet[] reloadedTreets = Treets.load();
    for(Treet reloaded : reloadedTreets){
      System.out.println(reloaded);
    }
  }
}

package com.teamtreehouse;

import java.io.Serializable;
import java.util.Date;

public class Treet implements Comparable, Serializable{
  //private boolean mBreakIt = true;
  private String mAuthor;
  private String mDescription;
  private Date mCreationDate;

  public Treet(String author, String description, Date creationDate){
    mAuthor = author;
    mDescription = description;
    mCreationDate = creationDate;
  }

  @Override
  public String toString(){
    return String.format("Treet: \"%s\" by %s on %s",
                         mDescription, mAuthor, mCreationDate);
  }

  @Override
  public int compareTo(Object obj){
    Treet other = (Treet) obj;
    if (equals(other)){
      return 0;
    }
    int dateCmp = mCreationDate.compareTo(other.mCreationDate);
    if (dateCmp == 0){
      return mDescription.compareTo(other.mDescription);
    }
    return dateCmp;
  }

  public String getAuthor(){
    return mAuthor;
  }

  public String getDescription(){
    return mDescription;
  }

  public Date getCreationDate(){
    return mCreationDate;
  }

  public String[] getWords(){
    return mDescription.toLowerCase().split("[^\\w#@']+");
  }
}

package com.teamtreehouse;

import java.io.*;

public class Treets{

  public static void save(Treet[] treets){
     try(
      FileOutputStream fos = new FileOutputStream("treets.ser");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
     ){
      oos.writeObject("treets");
     } catch(IOException ioe){
      System.out.println("Problem saving Treets");
      ioe.printStackTrace();
     }
  }

  public static Treet[] load() {
    Treet[] treets = new Treet[0];
    try (
      FileInputStream fis = new FileInputStream("treets.ser");
      ObjectInputStream ois = new ObjectInputStream(fis);
    ) {
      treets = (Treet[]) ois.readObject();
    } catch(IOException ioe) {
      System.out.println("Error reading file");
      ioe.printStackTrace();
    } catch(ClassNotFoundException cnfe) {
      System.out.println("Error loading treets");
      cnfe.printStackTrace();
    }
    return treets;
  }
}

3 Answers

Alexander Nikiforov
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 Points

The problem is very simple actually, but hard to find.

You are NOT saving 'treets' array but saving string "treets". Look at the lecture once again and change the following line:

      oos.writeObject("treets"); // just some String

TO

      oos.writeObject(treets); // actual array passed as argument

So what happened is that you saved String "treets" but not the array. That is why when you call load program cannot cast String to Treets[].

So uncomment your saving code in Example.

Change Treets.save method like I said.

Re-save treets.

Type cat treets.ser to make sure you see Treets and not Strings ( check with lecture)

And the you can comment "save" part in Example and use just "load" part

Does it make sense?

Joel Wood
Joel Wood
6,327 Points

Wow! This was very informative. You helped me fix the problem, and I learned something new.

Thank you, Alexander and Tomas, for all the help!

-Joel

Tomas Schlepers
Tomas Schlepers
18,039 Points

This exception means that two types are not castable. Think of it as apples and peares (IF spelled correct!). You cannot convert an apple into a pear.

In this case, you are trying to print out your object as a whole, and after that the seperate words. When trying to print your object as a String, you need to call the toString() method on it, like this :

System.out.printf("This is a new Treet: %s %n", treet.toString());

Hope this helps!

Alexander Nikiforov
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 Points

Both statements will have same result

System.out.println(object.toString());

and

System.out.println(object);

Because PrintStream.println has an overload, so it will call toString method for you.

Check here for more:

http://stackoverflow.com/questions/8555771/why-is-the-tostring-method-being-called-when-i-print-an-object

http://stackoverflow.com/questions/16570937/tostring-method-within-system-out-println-a-double-call

What is more important.

If you write:

System.out.println(object.toString());

It will throw NullPointerException

Whereas

System.out.println(object);

will print null without exception, which is number one of the reason at least for me not to use toString() explicitly.