Java Java Data Structures Organizing Data Comparable

Leo Marco Corpuz
Leo Marco Corpuz
18,975 Points

Sorting dates

I’m not sure how to do this part of the challenge. I got lost when watching this part of the lecture.

com/example/BlogPost.java
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 int compareTo(Object obj){
  BlogPost castObj=(BlogPost)obj;
  if(equals(castObj)){
  return 0;
  }

  return 1;
  }
  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;
  }
}

3 Answers

Tonnie Fanadez
Tonnie Fanadez
UX Design Techdegree Graduate 22,771 Points

Hi Leo Marco Corpuz

Part 1 is the easiest part; you just use keywords implements Comparable to make class BlogPost implement Comparable Interface.

public class BlogPost implements Comparable {}

You then generate the compareTo() method with an int as the return type.

public int compareTo(Object other){ return 1; }

Tonnie Fanadez
Tonnie Fanadez
UX Design Techdegree Graduate 22,771 Points

Part Two

We down cast the Object other to a BlogPost and then check if the current (this) BlogPost object is equal to the other BlogPost Object. If the BlogPost Objects are equal we return 0 - zero.

  public int compareTo(Object other){
    BlogPost post =(BlogPost)other;

    if(equals(other)){ 
     //you could also write the above line as --->>> if(this.equals(other)){}
    return 0;
    }
  return 1;
  }
Tonnie Fanadez
Tonnie Fanadez
UX Design Techdegree Graduate 22,771 Points

Part Three

Use compareTo() method to return either a negative or a positive int depending on whether the first object is less or greater than the second.

Hope this clarifies.

public int compareTo(Object other){
    BlogPost post =(BlogPost)other;

    if(equals(other)){
    return 0;
    }
  return mCreationDate.compareTo(post.getCreationDate());
  }

See you around.