I have an array of Class Customer
. I would like to alphabetically re-order the elements in the array of Class Customer
based on a field called name
.
Here is the code I am using:
int j;
boolean flag = true; // will determine when the sort is finished
Customer temp;
while ( flag )
{
flag = false;
for ( j = 0; j < count_customers; j++ )
{
if ( customers[ j ].getName().toString().compareToIgnoreCase( customers[ j + 1 ].getName().toString() ) > 0 )
{
temp = customers[ j ];
customers[ j ] = customers[ j+1 ]; // swapping
customers[ j+1 ] = temp;
flag = true;
}
}
}
customers[]
is the array that holds Customer
count_customers
represents the number of active customers.
for some reason when I run the code below returns nothing:
for(int i=0; i < count_customers; i++)
{
tmp_results += customers[ i ].toString() + "\n";
}
.toString()
is defined in Customer
class, it just prints everything about the customer out.
So what am I doing wrong?
Create a new class CustomerComparator
and sort your Customer[]
using Arrays.sort(array, new CustomerComparator());
public class CustomerComparator implements Comparator<Customer> {
@Override
public int compare(Customer c1, Customer c2) {
return c1.getName().compareTo(c2.getName());
}
}