File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes How to sort Arraylist without Sort method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to sort Arraylist without Sort method" Watch "How to sort Arraylist without Sort method" New topic
Author

How to sort Arraylist without Sort method

Rajendra Prakash
Ranch Hand

Joined: Sep 10, 2009
Posts: 293
How to sort Arraylist without Collections.sort(alist). Is there any option sort arraylist objects
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

By implementing a sort algorithm (e.g bubble sort) yourself.


[My Blog]
All roads lead to JavaRanch
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19538
    
  16

You'll have to use get(int) and set(int, E) extensively to swap elements.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36453
    
  15
Might be better to dump the contents of the List into an array, sort the array, and create a new List from the sorted array.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19538
    
  16

I think that if Rajendra doesn't want to use Collections.sort (or isn't allowed to, perhaps this is a homework assignment) that Arrays.sort is also out of the question.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36453
    
  15
I didn't mean to use Arrays#sort, but to implement a sorting algorithm on the resultant array.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19538
    
  16

Ah right. I thought that with "sort the array" you meant using Arrays.sort.

That said, I don't see what advantage the arrays give you when sorting an ArrayList. The latter's get and set methods are just as fast as direct array access. (Granted, for a LinkedList it would probably be wiser to first extract the data.)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36453
    
  15
Direct array access might be easier for a newbie to visualise than get(123) and set(123, foo). At least that is what I was thinking. . . .
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to sort Arraylist without Sort method
 
Similar Threads
how to compeer Arraylist contains hashtables by key name
Ordering objects in a hashtable..............
how we sort arraylist contents
ArrayList sorting
Sorting with two fields