簡體   English   中英

電話簿按字段的​​字母順序排序

[英]Phonebook Alphabetical Sorting according to the field First Name

我正在嘗試獲取電話簿的JavaFx應用程序,以便根據名字按字母順序對聯系人列表進行排序。 但是,現有的循環沒有按正確的順序列出名稱。 這是排序方法:

 public static void sortContactList() {
        try {
        for (int i = 0; i < contactList.length - 1; i++) {
            for (int j = i + 1; i < contactList.length; j++) {
                if ((contactList[j].first.toCharArray()[0]) < (contactList[i].first.toCharArray()[0])) {
                    Entry tmp = contactList[j];
                    contactList[j] = contactList[i];
                    contactList[i] = tmp;
                }
            }
        }
    } catch (NullPointerException exc) {}
}

下面顯示了聯系人列表的組成方式。 它存儲在一個文件中,該文件的名字首先是該人的名字作為字符串:

class Entry {
public String first, last, number, note;
}
public class Phonebookfor1510 {
public static Entry[] contactList;
public static int num_entries;
public static void main(String args[]) throws Exception {
    int i;
    char C;
    String code, Command;
    contactList = new Entry[200];
    num_entries = 0;

我的其余代碼都可以使用。 我只是想知道為什么它沒有按字母順序對值列表進行排序。 任何幫助將不勝感激!!

您可以做的最好的事情是使用TreeSet。 像給定的例子

TreeSet<String> stringSet = new TreeSet<>();
        stringSet.add("Mummy");
        stringSet.add("Mahima");
        stringSet.add("Gaurav");
        stringSet.add("Naresh");
        stringSet.add("Bhawna");

        for(String s : stringSet) {
            System.out.println(s);
        }

輸出: Bhawna Gaurav Mahima媽咪Naresh

我認為沒有NullPointerException ,第二個for循環將永遠不會結束。 您正在增加j ,但要檢查i<contactList

在這種情況下,您可以使用Arrays.sort()

看一下這個示例代碼:

public class Entry implements Comparable<Entry>{
    private Long id;
    private String fullName;
    private String phoneNumber;

    public int compareTo(Entry other) {
        if(other==null) throw new NullPointerException();
        /*
        -1 : phonenumber of current entry is smaller that other
        0  : phonenumber of current entry is equal to other
        +1 : phonenumber of current entry is greater than other
         */
        return (this.getFullName().compareTo(other.getPhoneNumber()));
    }
    public static void main(String[] args){
        Entry[] entriesArray = getEntriesArrayListFromSomewhere();
        Arrays.sort(entriesArray);
    }

   //getters ans setters
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM