我搜索但找不到关于如何对我自己的通用集合类进行排序的任何答案。
我有这四个类:
第二次编辑 简化代码,应用了 Evgeniy 的建议,但仍然没有排序,连线:\
轨道类:
public class Track {
private Integer id;
private String interpreter;
private String title;
Track(int id,String interpreter,String title) {
this.id=id;
this.interpreter=interpreter;
this.title=title;
}
public String getInterpreter() {
return this.interpreter;
}
public String getTitle() {
return this.title;
}
public int getID() {
return this.id;
}
public String getCompleteName() {
return this.id+"\t"+this.interpreter.toString()+" - "+this.title.toString();
}
}
一个 TrackContainer 类:
import java.util.ArrayList;
import java.util.Iterator;
public class TrackContainer<T> extends ArrayList<T> {
private static final long serialVersionUID = 1L;
ArrayList<T> arraylist;
TrackContainer() {
arraylist = new ArrayList<T>();
}
public boolean insertTrack(T track) {
if(arraylist.add(track))
return true;
return false;
}
public void listAllTracks(java.util.Iterator<T> iterat) {
while(iterat.hasNext()) {
System.out.println(iterat.next());
}
}
public Iterator<T> iterator() {
// TODO Auto-generated method stub
return arraylist.iterator();
}
}
TrackIDComparator 类:
import java.util.Comparator;
public class TrackIDComparator implements Comparator<Track> {
@Override
public int compare(Track t1, Track t2) {
// TODO Auto-generated method stub
Comparable id1 = (Comparable)(t1.getID());
Comparable id2 = (Comparable)(t2.getID());
return id1.compareTo(id2);
}
}
最后是 Main 类:
import java.util.Collections;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
TrackContainer<Track> ltc = new TrackContainer<Track>();
ltc.insertTrack(new Track(2,"trackname1","tracktitle1"));
ltc.insertTrack(new Track(1,"trackname2","tracktitle2"));
ltc.insertTrack(new Track(3,"trackname3","tracktitle3"));
System.out.println("unsorted:");
Iterator<Track> it = ltc.iterator();
while(it.hasNext()) {
System.out.println(it.next().getCompleteName());
}
System.out.println("sorted:");
Collections.sort(ltc,new TrackIDComparator());
Iterator<Track> it2 = ltc.iterator();
while(it2.hasNext()) {
System.out.println(it2.next().getCompleteName());
}
}
}
输出:
未分类: 2 曲目名称 1 - 曲目标题 1 1 曲目名称 2 - 曲目标题 2 3 曲目名称 3 - 曲目标题 3 排序: 2 曲目名称 1 - 曲目标题 1 1 曲目名称 2 - 曲目标题 2 3 曲目名称 3 - 曲目标题 3