2013-03-25 55 views
0

我有一個類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類中定義的,它只是打印有關客戶的一切了。

那麼我做錯了什麼?

+0

Customer[]你怎麼設置count_customers的價值? – Philipp 2013-03-25 22:36:23

+0

'count_customers'正在工作,我只是簡單地在添加新客戶時運行'count_customers ++' – 2013-03-25 22:38:31

+0

(不相關,但考慮給你的旗子一個有意義的名字。) – 2013-03-25 22:38:53

回答

5

創建一個新類CustomerComparator和排序使用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()); 
    } 

} 
+0

或者如果您無法更改客戶,請爲其創建一個比較器。 – SirPentor 2013-03-25 22:40:46

+0

我不能編輯客戶,我如何創建比較?你能解釋一下嗎? – 2013-03-25 22:41:37

+0

我編輯了答案 – chopchop 2013-03-25 22:44:33