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 trialMehmet Arabaci
4,432 PointsComparable task 2 of 3 help.
Hi in the Java Data Structures course within learn Java I'm stuck on task 2 of 3. The code I have:
@Override
public int compareTo(Object obj) {
BlogPost temp = (BlogPost) obj;
if (temp.equals(obj)) {
return 0;
}
return 1;
}
and I've seen this code on other forum posts but it was never explained well enough why it's not working and what needs to change. The error message that comes back is looks like task 1 is not working now. Task one was meant to return 1. Very confused!!
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 temp = (BlogPost) obj;
if (obj.equals(temp)) {
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;
}
}
2 Answers
Trent Christofferson
18,846 PointsWhen you cast something you need to make sure it is of that type. Use an if statement using instance of to see if it is an instance of BlogPost
Mehmet Arabaci
4,432 PointsOkay I did that now but same error: "Oops! It looks like Task 1 is no longer passing." Task one was meant to return 1.
@Override
public int compareTo(Object obj) {
if (obj instanceof BlogPost) {
BlogPost temp = (BlogPost) obj;
if (temp.equals(obj)) {
return 0;
}
}
return 1;
}