Meaningless Drivel is fun!*
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
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: 19651
    
  18

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: 37970
    
  22
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: 19651
    
  18

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: 37970
    
  22
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: 19651
    
  18

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: 37970
    
  22
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. . . .
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How to sort Arraylist without Sort method
 
Similar Threads
how we sort arraylist contents
how to compeer Arraylist contains hashtables by key name
Sorting with two fields
ArrayList sorting
Ordering objects in a hashtable..............