Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Sorting a vector

Rebecca Abraham
Ranch Hand
Posts: 37
Hi,
I have a vector whose eah element is another vector. The elements of the inner vector are the name and other details of different people. My code needs to display the details of all the people name-wise in an alphabetical order as shown below:
Ann 12-12-1968
Bob 20-10-1950
Jon 05-11-1970
Mary 01-01-1972
Is there some way 2 do this? Thanx in advance.
Rebecca

Avi Abrami
Ranch Hand
Posts: 1141
1
Hi Rebecca,
Pardon me if I am stating the obvious here, but perhaps one of the "sort" methods (in class "java.util.Arrays") is appropriate?
Hope this helps.
Good Luck,
Avi.

Rebecca Abraham
Ranch Hand
Posts: 37
Hi Avi,
Thank you for the response. but i think my question was a bit vague. I have a vector A with 5 elements. Each element of A is another vector. The first element of A, say A1, contains 2 elements - "Ann", "12-12-1956". The second element of A, say A2, also has 2 elements - "Bob","19-10-1970" and so on. When displaying i need to display each user and the corresponding date. But the display must be in alphabetical order. My code is roughly as follows:
Vector rsVect = new Vector();
Vector vect;
int i = 0;
while (count<=5)
{
vect = new Vector();

i++;
}
for (int i = 0; i < 5; i++)
{
Vector vTemp = (Vector) rsVect.elementAt(i);
String cTemp = (String) vTemp.elementAt(0);
System.out.print(cTemp + " "));
cTemp = (String) vTemp.elementAt(1);
System.out.println(cTemp));
}
Is there some way to get the names to be printed in an alphabetial order at this retrieving point?
Rebecca

Peter den Haan
author
Ranch Hand
Posts: 3252
Yes, the sort methods will work, you just have to write your own Comparator. Two things though
• It seems as if you're using Vector to represent structured data -- isn't that what classes where invented for?
• Please use ArrayList instead of Vector, HashMap instead of Hashtable, and Iterator instead of Enumeration. These classes are bloated, obsolete, outside the Collections framework, and encourage you to write thread-unsafe code.
• HTH
- Peter

Avi Abrami
Ranch Hand
Posts: 1141
1
Peter,
Actually, I was hoping that Rebecca would read the "javadoc" for the "sort()" method, 'discover' the "Comparator" interface, and realize that it may present a viable solution for her problem.
Unfortunately, it would seem that Rebecca did not proceed along the path that I had envisaged for her.
Nonetheless, you have given her another "nudge" in that direction. I hope it is sufficient to progress her toward a satisfactory solution (for her).
[When she asks, "how do I write a 'Comparator'?", I promise I'll let you do the honours ;-]
Cheers,
Avi. :roll:

Rebecca Abraham
Ranch Hand
Posts: 37
Thank you. I'll try it out.
Rebecca