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 Efficiency! Custom Serialization

CompareTo is a method in the Interface Comparable

CompareTo is a method in the Interface class Comparable. How comes that Craig using it here: Since he doesnt implements Comparable where the method compareTo exist. Craig is implementing Comparator wich have the method compare.

I would also say Craig is importing the Interface Comparator. I think its wrong what i learned from the book is that we have to Implement Interface classes?

public List<Song> getSongsForArtist(String artistName){ List<Song> songs = byArtist().get(artistName); songs.sort(new Comparator<Song>(){

 @Override
 public int compare(Song song1, Song song2){
    if(song1.equals(song2)){
    return 0; 
    }
   return song1.mTitle.compareTo(song2.mTitle); 
  }
 });    
return songs;

}

1 Answer

Evgeniia Vakarina
Evgeniia Vakarina
3,317 Points

The link about Anonymous Classes in the teachers notes is good for this question, I think (http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html). There are different situations and some times you need to implement an interface, sometimes (esp. if you are going to use it just in that one place) you would want to just use an anonymous class.

Evgeniia Vakarina
Evgeniia Vakarina
3,317 Points

and if you're asking how come he uses compareTo here - return song1.mTitle.compareTo(song2.mTitle); - it's just he uses the String's compareTo method on the String, that's why it's ok, you can actually call it everywhere on a String, and you wouldn't need to implement anything