Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Data Structures 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