Comparator排序的使用 来自head first java

import java.util.*;
import java.io.*;

public class Jukebox5{
  ArrayList<Song> songList=new ArrayList<Song>();
  public static void main(String[] args){
    new Jukebox5().go();
  }

  class ArtistCompare implements Comparator<Song>
  {
	  public int compare(Song one,Song two){
	     return one.getArtist().compareTo(two.getArtist());
	  }
  }
  class RatingCompare implements Comparator<Song>
  {
	  public int compare(Song one,Song two){
	     return one.getRating().compareTo(two.getRating());
	  }
  }
  //Comparator类多好,想按什么排序就按什么排序
  //用sort(List o)以及实现compareTo()就不行喽
  public void go(){
    getSongs();
    System.out.println(songList);
    //Collections.sort(songList);
	//System.out.println(songList);
    //这个排序现在仍然可以用

    ArtistCompare artistCompare=new ArtistCompare();
	Collections.sort(songList,artistCompare);
	System.out.println(songList);

	RatingCompare ratingCompare=new RatingCompare();
	Collections.sort(songList,ratingCompare);
	System.out.println(songList);
  }

  void getSongs(){
    try{
	  File file=new File("SongListMore.txt");
	  BufferedReader reader=new BufferedReader(new FileReader(file));
	  String line=null;
	  while((line=reader.readLine())!=null){
	    addSong(line);
	  }
	}catch(Exception ex){
	  ex.printStackTrace();
	}
  }

  void addSong(String lineToParse){
    String[] tokens=lineToParse.split("/");

	Song nextSong=new Song(tokens[0],tokens[1],tokens[2],tokens[3]);
	songList.add(nextSong);
  }

}

/*
☆调用单一参数的sort(List o)方法代表由list元素上的compareTo()方法来决定顺序。因此元素必须要实现Comparable这个几口。

☆调用sort(list o,Comparator c)方法代表不会调用list元素的compareTo()方法,而会使用Comparator的commpare()方法。这意味着list元素不需要实现Comparable。
*/

你可能感兴趣的:(java,C++,c,C#,Go)