以下是在LinkedList中查找排序索引的一種方法。
import java.util.*;
public class SortedLinkedListDemo {
public static void main (String [] args) {
List<String> list = new LinkedList<String>();
list.add ("Dusty");
list.add ("Gordon");
list.add ("Mayer");
list.add ("Popovic");
list.add ("Zechariah");
list.add (getSortedIndex ("Nyugen", list), "Nyugen");
System.out.println ("List: "+list);
}
private static int getSortedIndex (String name, List<String> list) {
for (int i=0; i < list.size(); i++) {
if (name.compareTo(list.get(i)) < 0) {
return i;
}
}
// name should be inserted at end.
return list.size();
}
}
這會給下面的輸出:
列表:塵土飛揚,戈登,邁耶,Nyugen,波波維奇,撒迦利亞]
鏈表不會做這個,但是PriorityQueue會。請參閱http://stackoverflow.com/questions/416266/sorted-collection-in-java – lreeder