0
 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.

2
  • 1) For better help sooner, post an SSCCE. 2) Please don't forget to add a '?' to questions! Some people do a search in the page for '?' and if none exists in the 'question' go directly to the next (actual) question in line. Commented Dec 15, 2013 at 18:24
  • Assuming your PhoneBooks aren't comparing by Telephone Number, you could write a PhoneBookComparator and use Collections.sort(). Commented Dec 15, 2013 at 18:32

4 Answers 4

2

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());
Sign up to request clarification or add additional context in comments.

5 Comments

I understand the part where you are comparing the 2 Telephone numbers but where would I do do Collections.sort(list, new CustomComparator());?
It depends in when and where you want to sort your ArrayList.
I only want to sort the Phone Numbers not the whole ArrayList as a PhoneBook object stores other attributes such as name, address etc...
So you want another ArrayList with just the telephones sorted?
Looks like another collection is the only way to sort the telephones only... but I'm going to have to loop again and that increases time complexity
0

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

Comments

0

You can use the java.util.Collections for that.

Comments

0

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

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

Collections.sort(nameOfList)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.