sorting by alphabeticial order
Ok...I have a Vector of Person objects which contans a first, last, adress, and phone number. I need to be able to sort this Vector three ways by first, last, and the address. I don't care about the phone number.
My Person class extends Comparable and has a compareTo method. Problem is, I am not sure what the best manner of sorting is. I would like to read in the Vector of Objects (which is originally sorted by Last name, this is given to me) from disk and then create the sorted by adress and phone number vectors. I would like to do an insertion-sort but am not sure what type is the best. Binary-insertion sort perhaps? I'm not very skilled in this type of programming. I suppose I am asking given this information, what is the best method of sorting and perhaps for a code sniplet to get me going.
If more information is needed, let me know.
Thanks in advance,
Travis.
First of all, you can use the method java.util.Collections.sort(java.util.List). To do this, the objects of the Vector should implement Comparable.
However, this will only make it possible to sort the list according to one sorting rule. Instead you should write three classes implementing the Comparator interface - one for each sorting (or perhaps just one Comparator that can be configured), and pass objects of these Comparators to the sort() method.
Something like this should sort the persons on address:
class AddressComparator implements Comparator {
int compare(Object v1, Object v2) {
Person p1 = (Person)v1;
Person p2 = (Person)v2;
return p1.getAddress().compareTo(p2.getAddress());
}
}
...
Vector persons;
// read in persons here
// ...
java.util.Collections.sort(persons, new AddressComparator());
// here persons will be sorted by address
Regards,
Søren Bak
maybe somethig like that:
class Person implements Comparable{
static final int BY_FIRSTNAME=0;
static final int BY_LASTNAME=1;
static final int BY_ADDRESS=2;
static int comparison=BY_FIRSTNAME;
private static void setComparison(int comparison){
this.comparison=comparison;
}
public int compareTo(Object obj){
....
}
}
Hi,
welkeidkiezen has the best solution, imho.
We had a similar situation, where the user had to sort the data in a collection by any column - actually, the collection was displayed as a table, and the user clicked a column heading to sort by that column.
We just used static final variables to specify the column to sort and the direction to sort (ascending or descending) and wrote the compareTo() method so that it checked these variables before comparing.
The rest of the work was done by Arrays.sort().