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

James Dunn
James Dunn
3,041 Points

Java Comparable challeng, task 2, resulting in task one failing.

So my understanding of the task and code I've written suggests to me that the code is solid. However, when I submit my answer it says task one is no longer working but it passes just fine when I go back and resubmit task 1.

Simply put, I have no idea what I'm missing and need help figuring it out.

Thanks all.

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

import java.util.*;
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;
  }

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

    if(post == obj) {
      return 0;
    }
    return 1;

  }
}

1 Answer

Leandro Botella Penalva
Leandro Botella Penalva
17,618 Points

Hi James,

You are comparing the same objects. obj and post are the same. Also, to compare an object use the method equals instead of == comparison. The == comparison checks only if both objects point to the same memory place or in other words are the same instance.

You should compare the element that called compareTo (this) and the casted object passed as the parameter .

BlogPost post = (BlogPost)obj;
if (this.equals(post)) {
    return 0;
}
return 1;

This is a better way of doing it. This method checks first if the object belongs to BlogPost:

if (obj instanceof BlogPost) {
    BlogPost post = (BlogPost)post;
    if (this.equals(post)) {
        return 0;
    }
}
return 1;