开发者

Java Comparable<T> interface

In the book I'm reading (Head First Java) stated that when I'm开发者_JAVA技巧 calling Collections.sort(myList) (where myList is a ArrayList<Song> object and Song class implements Comparable<Song> interface) the compareTo() method will be called on one Song object, passing that Song a reference to a different Song.

I just can't get how it is passing a reference to a different Song, how can it know about different one?


Imagine that there were no such thing as a Collection and you had to write your own sort() method from scratch. Let's try it with the (stupidly slow but easy to understand) bubble sort algorithm. In general, that looks something like this:

for (int i = 0; i < myList.length; i++) {
    for (int j = i; j < myList.length; j++) {
        if (myList[i] < myList[j]) {
            Song temp = myList[i];
            myList[i] = myList[j];
            myList[j] = temp;;
        }
    }
}

Of course, myList[i] < myList[j] won't work. You need a function to compare the two objects and determine which one is greater. So the actual code would look like:

if (myList[i].compareTo(myList[j]) < 0) {

And there are your two Song objects: the object on which you're calling the method (myList[i]) and the object you're passing as a parameter.


It grabs pairs of songs out of the ArrayList and passes one to the .compareTo of another.


It takes the first song from the list, takes the second one, and calls the song1.compareTo(song2) where song1 is the first song, and song2 is the second. You might want to implement any sort algorithm manually.


The way to sort objects to to somehow compare each one to all the others. So you can take the first Song in the list and compare it to each of the other songs until you find where it goes. It then have to decide where the second song goes by comparing it to all other songs etc. This describes an insertion sort algorithm but you get the idea...


You are always comparing two songs (different or not, does not matter). See the following example:


package edu.androidnoob.test.comparable;

import java.util.List;

public class ComparableTester {

  public static void main(String[] args) {
    List songs = new ArrayList();
    songs.add(new Song("Poker Face"));
    songs.add(new Song("November Rain"));
    System.out.println("Are songs different? "
        + (songs.get(0).compareTo(songs.get(1)) != 0));
    System.out.println("Are songs different? "
        + (songs.get(0).compareTo(songs.get(0)) != 0));
  }

  private static final class Song implements Comparable<Song> {
    private String name;

    public Song(String name) {
      this.name = name;
    }

    public String getName() {
      return name;
    }

    public int compareTo(Song song) {
      return this.name.compareTo(song.getName());
    }

  }

}

And see the output:

Are songs different? true
Are songs different? false
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜