Reputation: 756
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.
Upvotes: 0
Views: 333
Reputation: 18572
The best will be use standart way with java.util.Collections
String class has method compareTo()
and will be sorted automtically:
Collections.sort(nameOfList)
Upvotes: 0
Reputation: 34146
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());
Upvotes: 2
Reputation: 901
You can use the java.util.Collections class to sort the lists. Use Collections.sort().
Upvotes: 0