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 trialChris Shearon
Courses Plus Student 17,330 PointsStuck again. Order the creation date, oldest first?
In step 3 of the challenge, do I add an arrays.sort to the obj? Create a new method? I'm lost here. I've watched the video several times over and either I'm just not getting it or it's not being explained very well.
package com.example;
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;
}
@Override
public int compareTo(Object obj) {
BlogPost other = (BlogPost) obj;
if (equals(other)) {
return 0;
}
return 1;
}
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;
}
}
1 Answer
Dan Johnson
40,533 PointsYou'll be modifying the compareTo method in order to compare the Date
properties between the two.
You can leverage the compareTo method of Date to determine the order.
Chris Shearon
Courses Plus Student 17,330 PointsChris Shearon
Courses Plus Student 17,330 PointsThanks for explaining it. I passed the challenge but I still don't completely understand.
Dan Johnson
40,533 PointsDan Johnson
40,533 PointsIf you're still wondering about compareTo, here's how it works:
When implementing the
Comparable
interface you can define which type you want this object to be comparable with using generics (Or keep it asObject
and just cast).Then you determine what makes the object you're comparing against less than, equal to, or greater than and assign the following values:
If the object is less than the calling object, return -1:
If the object is equivalent to the calling object, return 0:
Or if the object is greater than, return 1:
For a more concrete example, here's a sample application thrown together in Workspaces using
Date
:If it was something else you weren't sure about just leave another comment and I'll see if I can explain it.