类的数组的字母顺序

Aho*_*tbi 0 java sorting bubble-sort java-7

我有一个Class数组Customer.我想按字母顺序重新排序Class数组中Customer基于所调用字段的元素name.

这是我正在使用的代码:

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;
                 } 
             } 
         } 
Run Code Online (Sandbox Code Playgroud)

customers[]hold Customer count_customers表示的数组表示活动客户的数量.出于某种原因,当我运行以下代码时,什么都不返回:

        for(int i=0; i < count_customers; i++)
        {
            tmp_results += customers[ i ].toString() + "\n";
        }
Run Code Online (Sandbox Code Playgroud)

.toString()Customer课堂上定义,它只是打印出客户的一切.

那么我做错了什么?

cho*_*hop 5

创建一个新类CustomerComparator并对您的Customer[]使用进行排序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());
    }

}
Run Code Online (Sandbox Code Playgroud)