我有一个Customer
类数组。我想根据名为 name
的字段按字母顺序重新排序 Customer
类数组中的元素。
这是我正在使用的代码:
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[]
是保存 Customer
的数组
count_customers
表示活跃客户数量。
由于某种原因,当我运行下面的代码时什么也没有返回:
for(int i=0; i < count_customers; i++)
{
tmp_results += customers[ i ].toString() + "\n";
}
.toString()
是在 Customer
类中定义的,它只是打印出有关客户的所有信息。
那我做错了什么?
最佳答案
创建一个新类 CustomerComparator
并使用 Arrays.sort(array, new CustomerComparator()); 对
Customer[]
进行排序;
public class CustomerComparator implements Comparator<Customer> {
@Override
public int compare(Customer c1, Customer c2) {
return c1.getName().compareTo(c2.getName());
}
}
关于java - 类数组的字母顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15626096/