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!

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 Exploring the Java Collection Framework Upgrade Comparable to use Generics

jinhwa yoo
jinhwa yoo
10,042 Points

help me


  public class BlogPost implements Comparable<BlogPost>, Serializable {   //Notice the "Comparable<BlogPost>" part. This is what allows you to compare a BlogPost object to another BlogPost object.
public int compareTo(BlogPost other) {   //Create a BlogPost object named Other
/* BlogPost other = (BlogPost) obj;  */
    if (equals(other)) {
      return 0;

1 Answer

Harry James
Harry James
14,780 Points

Hey jinhwa!

We learnt about generics as part of the Interfaces video.

I'll quickly go over what one is again for you. A generic is a specific declaration of type, shown by a pair of angle brackets. For example, if we have a list and we get an item from it, we need to use casting:

List list = new ArrayList();
String s = (String) list.get(0);

but if we use a generic:

List<String> list = new ArrayList<String>();
String s = list.get(0);

We do not need to use casting, plus it's clearer to read what the list contains. This benefits us because if we do something wrong, we'll know about it at compile time, which is a lot easier to detect and fix than at runtime.

Armed with this information again, you should now be able to complete the challenge. What you want to do is update the Comparable interface to use the generic type of BlogPost. You should also update the compareTo() so that it no longer uses just an Object, and instead uses the more specific BlogPost class.