2

I have a LinkedList called recordInformation that contains an object at each index. The object consists of a first name, last name, numnbr, and balance separated by spaces. So recordInformation looks like [[firstName lastName number balance][fname lastname number bal]]. Everytime I add a record to recordInformation, I sort the list based on last name. I've attempted to write a method, but when I output the list in another method, the indexes have not changed. Is compareTo the correct way to check for alphabetical order?

public void sortRecords(LinkedList list){
    if (list.size()==1)
        return;

    Object obj = recordInformation.getLast();
    String sortVar = obj.toString();
    String[] varArray = sortVar.split(" ");

    for (int i=0;i<list.size();i++){
        Object obj1 = recordInformation.get(i);
        String compare = obj1.toString();
        String[] compareArray = compare.split(" ");
        //varArray[1] and compareArray[1] hold the last names
        if ((varArray[1].compareTo(compareArray[1]))<0){
            recordInformation.add(i,obj);
            recordInformation.remove(list.size()-1);
        }

    }

}
4

2 回答 2

0

如果您想保持排序顺序并同时在插入时做很多事情,那么LinkedList这是最后使用的数据结构之一。

你所追求的是红黑树。在java中它被实现为java.util.TreeMap

于 2013-03-26T00:01:59.883 回答
0

如果您从一开始就控制了列表,为什么不将元素插入正确的位置?

我的意思是如果有A,你需要放C,然后放A->C,如果有B,那么放A->B->C。这样你就不会使用 Collections.sort (或任何排序)。

于 2013-03-25T23:44:30.463 回答