Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Java (http://www.programmingforums.org/forum17.html)
-   -   Sorting an array of objects (http://www.programmingforums.org/showthread.php?t=8533)

oNe8 Feb 22nd, 2006 9:59 PM

Sorting an array of objects
 
Ok this one has me pretty stumped for something that should seem very simple.

SO i have an object[] that i need to sort by in alabetical order by the String returned by object.getName(). I suspose this can be done some how by using Arrays.sort(object[], Comparator c) but i have no idea how i would go about that.

I the only reason i really want the array sorted it just so i can save processing power by using a binary search later on rather then brute forcing the hell out of the array.

jaeusm Feb 22nd, 2006 10:40 PM

You could just implement one of the more efficient sort algorithms, like merge sort or quicksort. It doesn't require much effort.

titaniumdecoy Feb 22nd, 2006 10:59 PM

Create a class, say ObjectNameComparator, that extends Comparator and implements public int compare(Object obj1, Object obj2) and returns -1 if obj1 is larger than obj2, 0 if they are the same, and 1 if obj1 is smaller.

In your main method, import java.util.Arrays. Create a new instance of ObjectNameComparator. Sort the array object[] using Arrays.sort(object, new ObjectNameComparator()).


All times are GMT -5. The time now is 7:38 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC