Sorting an array of objects

I need to sort an array of objects

Page 1 of 1

1 Replies - 4549 Views - Last Post: 28 March 2008 - 09:12 AM Rate Topic: -----

#1 mathews666  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 26-January 08

Sorting an array of objects

Posted 28 March 2008 - 07:59 AM

Now I need to sort them but conventional methods don't work.

name of the array of objects: vehicleArr
indexcounter a number of items on the array

I have loaded and figured it out how to print all the object in my array.

for(int i = 0; i < indexCounter; i++)
{
System.out.println(vehicleArr[i]);
}


I need to sort this array Helpppp!!!!!!!!!! it is an array of objects!

Is This A Good Question/Topic? 0
  • +

Replies To: Sorting an array of objects

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4354
  • View blog
  • Posts: 12,160
  • Joined: 18-April 07

Re: Sorting an array of objects

Posted 28 March 2008 - 09:12 AM

You need to use a comparator. A comparator is a special function you write which teaches Java how to compare custom user defined objects. You can then tie it into a sort call and the sort function will use the comparator to compare your objects for inequality. Luckily I have written about this very thing in my blog at the following link...

Martyr2's Programming Underground - Comparators in Java (Prepare to Compare)

In the blog I create a simple example program and use a comparator to compare a custom class I made called "score". Since Java doesn't know how to compare my score classes to know which is before the other in sort, I tell it how to compare them (by writing my comparator to show Java how to compare the two objects using an internal data member also called "score" which is an integer.

It is pretty straight forward and I step through the process. So this should guide you through what you need to know.

Enjoy! :)
Was This Post Helpful? 1

Page 1 of 1