不废话了 , 直接给大家贴代码了。
classe term {string str; int id; Term public (String str, int id) {this.str = str; this.id = id; } public String toString () {return str + "" + id; }} class ster implémente comparable {String str; int id; public sterm (String str, int id) {this.str = str; this.id = id; } public int compareto (objet o) {return ((ster) o) .id - id; } public String toString () {return str + "" + id; }} // Method1: Explicit implémente la classe de comparaison TermComparator implémente le comparateur {public int compare (objet o1, objet o2) {return ((Term) o1) .id - ((term) o2) .id; }} classe publique T1 {/ ** * @param args * / public static void main (String [] args) {// TODO Méthode générée automatique Stub // ArrayList <Integer> Arr = new ArrayList <Integer> (Arrays. aslist (3,1,3,7,8,0)); // // Collection.Sort (arr, new comparateur () {// // public int compare (objet o1, objet o2) {// return new double ((Integer) o1) .compareto (new double ((entier) o2)); //} //}); // Method1 list <ter> ls = new ArrayList <mor> (); ls.add (nouveau terme ("a", 1)); LS.ADD (nouveau terme ("B", 5)); LS.ADD (nouveau terme ("C", 2)); ls.add (nouveau terme ("d", 2)); LS.ADD (nouveau terme ("E", 3)); ls.add (nouveau terme ("f", 0)); Collection.Sort (LS, New TermComparator ()); System.out.println (ls); // [F 0, A 1, C 2, D 2, E 3, B 5] // Method2: Anonymous Implements Collection.Sort (LS, New Comparator () {public int compare (Objet o1, objet o2) {return ((terme) o2) .id - ((terme) o1) .id;}}); System.out.println (LS); // [B 5, E 3, C 2, D 2, A 1, F 0] // Méthode 3: Instancier un modèle de comparateur Comparateur <mor> termcmp = nouveau comparateur <mor> ( ) {public int compare (term t1, term t2) {return t1.id - t2.id; }}; Collection.Sort (LS, TermCMP); System.out.println (ls); // [F 0, A 1, C 2, D 2, E 3, B 5] // Method4: L'élément implémente la liste comparable <Sterm> lss = new ArrayList <Sterm> () ; LSS.ADD (New Sterm ("A", 1)); LSS.ADD (New Sterm ("B", 5)); LSS.ADD (New Sterm ("C", 2)); LSS.ADD (New Sterm ("D", 2)); LSS.ADD (New Sterm ("E", 3)); LSS.ADD (New Sterm ("F", 0)); Collection.Sort (LSS); System.out.println (LSS); // [B 5, E 3, C 2, D 2, A 1, F 0]}}Pririyqueue 的用法和上述的排序类似 , : :
class wordfreq implémente comparable {public string wd; public int freq; public wordfreq (String wd, int freq) {this.wd = wd; this.freq = freq; } public int compareto (objet o) {return ((wordfreq) o) .freq - freq; } public String toString () {return wd + "" + freq; }} classe publique testt {public static void main (String [] args) {// TODO Méthode générée automatique Stume priorityqueue <wordfreq> pq = new priorityqueue <wordfreq> (); pq.offer (new wordfreq ("aaa", 3)); pq.offer (new WordFreq ("BBB", 4)); pq.offer (new WordFreq ("CCC", 1)); while (pq.Peek ()! = null) {System.out.println (pq.poll ()); } // 从大到小输出}}注意 ,
for (wordfreq wf: pq) {System.out.println (wf);}并不保证遍历的有序
如果 Liste <string> ls 进行排序的话 , 不需要写 Comparator, 因为 String 本身有 compareto 的实现。