简体   繁体   中英

How to sort elements in an ArrayList of Strings?

 PhoneBookCollection phoneBook = new PhoneBookCollection();

I have an ArrayList of PhoneBook objects. (The getCollection method returns the list)

ArrayList<PhoneBook> list = phoneBook.getCollection();


I then iterate through my ArrayList and get the PhoneBook at the i'th index and get its corresponding Telephone .

for(int i = 0; i < list.size(); i++ ){

String phone = phoneBook.getPhoneBook(i).getTelephone();

}

What I want to be able to do now is sort the getTelephone objects in ascending order. I know that ArrayLists don't have a sort method so i'm having a bit of trouble doing this.

You can create a class that implements Comparator :

public class CustomComparator implements Comparator<PhoneBook> { // Replace PhoneBook with the appropriate
    @Override
    public int compare(PhoneBook t1, PhoneBook t2) {
        return t1.getNumber().compareTo(t2.getNumber()); // Here compare the telephone numbers
    }
}

Then do this:

Collections.sort(list, new CustomComparator());

You can use the java.util.Collections class to sort the lists. Use Collections.sort().

您可以使用java.util.Collections

The best will be use standart way with java.util.Collections

String class has method compareTo() and will be sorted automtically:

Collections.sort(nameOfList)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM