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

David Reese
David Reese
3,515 Points

How do I do this if I don't. know where the blog posts are instantiated; I don't have any array of all the blog posts

How do I do this if I don't. know where the blog posts are instantiated; I don't have any array of all the blog posts

com/example/BlogPost.java
package com.example;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;

public class BlogPost implements Comparable {
  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;
  }

  public int compareTo(Object object){
    BlogPost blogPost = (BlogPost) object;
    if(equals(blogPost)){
      return 0;
    }
    return 1;
  }

}
David Reese
David Reese
3,515 Points

It wants me to sort based on chronological order

1 Answer

Gergely Horvath
PLUS
Gergely Horvath
Courses Plus Student 8,207 Points

When implementing Comparable interface, you don't have think about the actual collection that you do the sorting on just yet. The scope if this interface is to declare how to relate two complex objects of the same type to each other in an orderly manner. Then the sort algorithm will put object pairs into this method to create the right order. In your code challange it is stated that there no creationDate duplications among the BlogPost objects by which your compareTo method will be tested. Thus you only need to return either -1 or 1 by looking at the creationDates of the subjects of the comparison.