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 Comparable

Gaspar Santiago
Gaspar Santiago
3,377 Points

Compiler error in return value. Instructions for this exercise are confusing.

Here is the source code along with comments and compiler error:

public int compareTo(Object obj) { BlogPost post = null;

if(obj.equals(post)){ //Check for equality first
  post = (BlogPost) obj; //In this step, cast the Object passed to the compareTo method to a com.example.BlogPost.
 return 0;  //if they are equal return 0. 
}
return 1; //Leave the default return of 1 in place for this step.
//Compiler error reads: Bummer! When an object `equals` another, the compareTo method should return 0. Current method returned 1.

}

I understand the method should return zero, but when the instructions are telling me to check for equality, and it should return 0 for equality but I should also leave the default return of 1, it makes things very confusing. I know this is wrong.

com/example/BlogPost.java
package com.example;

import java.util.Date;

public class BlogPost {
  private String mAuthor;
  private String mTitle;
  private String mBody;
  private String mCategory;
  private Date mCreationDate;

  public BlogPost(String author, String title, String body, String category, Date creationDate) {
    mAuthor = author;
    mTitle = title;
    mBody = body;
    mCategory = category;
    mCreationDate = creationDate;
  }

  public String[] getWords() {
    return mBody.split("\\s+");
  }

  public String getAuthor() {
    return mAuthor;
  }

  public String getTitle() {
    return mTitle;
  }

  public String getBody() {
    return mBody;
  }

  public String getCategory() {
    return mCategory;
  }

  public Date getCreationDate() {
    return mCreationDate;
  }
}