-4

Possible Duplicate:
How to sort an arraylist of objects java?

I have an arraylist that contains very large details i want to sort the data alphabetically but there is no method in arraylist class for sort. Please Help?

1
  • Huh didn't realize google was broken today.. Commented Dec 13, 2012 at 3:01

2 Answers 2

8

Use Collections.sort, which is able to sort any List.

I'm assuming that you're talking about a list of strings, in which case you can simply call Collections.sort on your list to sort it alphabetically.

If you're referring to a list of instances of a class you created with an internal string field then you have two options:

  • Have the class implement the Comparable interface, then call Collections.sort on the list with no arguments other than the list itself.

  • Write a custom Comparator that works with your class, and pass an instance of it to the sort method as a second argument along with your list.

If alphabetical ordering is the 'natural' way in which instances of your class should be ordered, you should probably implement Comparable. If not, you should probably write a Comparator.

Sign up to request clarification or add additional context in comments.

4 Comments

And write your own Comparator
@duffymo I was assuming it was a list of strings, but if not yes.
"array of objects" - no explicit mention of String.
@duffymo Alright, I updated my answer anyway, thanks for the notice.
5

There is no sort method in arraylist But there is a sort method in Collections as ArrayList comes under the collections tree structure you can use the sort of method in collections.Here is the code Collections.sort(arrayList);

3 Comments

Don't do that, you can see @A.R.S. already answered that.
Duplicates are bad. Accepted duplicates are worse. By the way not every collection is sortable.
I am not an java specialist all I wanted is to sort alone and not to get things complicated that is why i accepted this answer.But Your answer should elaborate well to other users who know java well.As I am new i choosed simple is best.Northing more in accepting your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.