Java Java Data Structures Efficiency! Custom Serialization

Araz kuberin
Araz kuberin
6,045 Points

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