[英]How to sort elements in an ArrayList of Strings?
PhoneBookCollection phoneBook = new PhoneBookCollection();
I have an ArrayList
of PhoneBook
objects. 我有一个PhoneBook
对象的ArrayList
。 (The getCollection method returns the list) (getCollection方法返回列表)
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
. 然后我遍历我的ArrayList并获取第i个索引的PhoneBook
并获得相应的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. 我现在想要做的是按升序对getTelephone
对象进行排序。 I know that ArrayLists don't have a sort method so i'm having a bit of trouble doing this. 我知道ArrayLists没有sort方法,所以我在这方面遇到了一些麻烦。
You can create a class that implements Comparator
: 您可以创建一个实现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. 您可以使用java.util.Collections类对列表进行排序。 Use Collections.sort(). 使用Collections.sort()。
您可以使用java.util.Collections 。
The best will be use standart way with java.util.Collections
最好的方法是使用java.util.Collections
标准方法
String class has method compareTo()
and will be sorted automtically: String类有方法compareTo()
,并将自动排序:
Collections.sort(nameOfList) Collections.sort(nameOfList)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.