Collections.sort(arraylist)

B

Bruce Lee

If I use Collections.sort(arraylist), the elements in the arraylist will be
sorted by natural order. What happens when the arraylist is actually an
arraylist of arraylists - how can you sort against an object?
 
T

Thomas Weidenfeller

Bruce said:
If I use Collections.sort(arraylist), the elements in the arraylist will be
sorted by natural order. What happens when the arraylist is actually an
arraylist of arraylists - how can you sort against an object?

"natural order" requires that the to-be-sorted elements in the List have
the Comparable interface implemented. If you use ArrayLists as elements
in the List you are out of luck, since ArrayList does not implement the
interface. Prepare for getting a ClassCastException.


/Thomas
 
R

Roedy Green

If I use Collections.sort(arraylist), the elements in the arraylist will be
sorted by natural order. What happens when the arraylist is actually an
arraylist of arraylists - how can you sort against an object?

you need to write a Comparator that compares entire ArrayLists in some
way e..g by number of elements.

see http://mindprod.com/jgloss/comparator.html
 
R

Roedy Green

If you use ArrayLists as elements
in the List you are out of luck, since ArrayList does not implement the
interface. Prepare for getting a ClassCastException.

you would have to extend your ArrayList and have it implement
Comparable and write some Comparators.
 
V

Viator

Or extend ArrayList to impelemnt Comparable interface to get the
desired behavior.

Amit :)
 
T

Thomas Hawtin

Thomas said:
"natural order" requires that the to-be-sorted elements in the List have
the Comparable interface implemented. If you use ArrayLists as elements
in the List you are out of luck, since ArrayList does not implement the
interface. Prepare for getting a ClassCastException.

Or compilation errors in current Java.

Tom Hawtin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top