2016-03-06 89 views
-1

所以我有一個程序,它用一個字符串和一個雙精度數字排列數組列表。我還必須按照字母順序對數組進行排序,而不用包含compareTo代碼的BankAccount類進行調試。Java可比較的接口故障

我只能修改包含在JavaCollections類中的比較滋擾。我一直認爲它與打印輸出有關,但我不確定。

下面是BankAccount類代碼:

import java.util.Collections; 

public class BankAccount implements Comparable<BankAccount>{ 
    private double balance; 
    private String owner; 

    public BankAccount(String owner, double balance) { 
     this.owner = owner; 
     this.balance = balance; 
    } 

    public double getBalance() { 
     return balance; 
    } 

    public String getName() { 
     return owner; 
    } 

    /** 
    Compares two bank accounts. 
    @param other the other BankAccount 
    @return 1 if this bank account has a greater balance than the other, 
    -1 if this bank account is has a smaller balance than the other one, 
    and 0 if both bank accounts have the same balance 
    */ 
    public int compareTo(BankAccount other) { 
     if(balance > other.balance) { 
      return 1; 
     } else if (balance < other.balance) { 
      return -1; 
     } else { 
      return 0; 
     } 
    } 
} 

,這裏是爲JavaCollections類的代碼,我可以修改:

import java.util.ArrayList; 
import java.util.Collections; 

public class JavaCollections extends BankAccount{ 

    public static void main(String[] args) { 
     // Put bank accounts into a list 
     ArrayList<BankAccount> list = new ArrayList<BankAccount>(); 
     BankAccount ba1 = new BankAccount ("Bob", 1000); 
     BankAccount ba2 = new BankAccount ("Alice", 101); 
     BankAccount ba3 = new BankAccount ("Tom", 678); 
     BankAccount ba4 = new BankAccount ("Ted", 1100); 
     BankAccount ba5 = new BankAccount ("Tom", 256); 

     list.add(ba1); 
     list.add(ba2); 
     list.add(ba3); 
     list.add(ba4); 
     list.add(ba5); 

     // Call the library sort method 
     Collections.sort(list); 

     // Print out the sorted list 
     for (int i = 0; i < list.size(); i++) { 
      BankAccount b = list.get(i); 
      System.out.println(b.getName() + ": $" + b.getBalance()); 
     } 
    } 

    public JavaCollections(String owner, double balance) { 
     super(owner, balance); 
    } 
} 
+0

什麼是此代碼打印。 ...? –

回答

0

您可以實現自定義Comparator類兩個BankAccount比較對象使用他們的名字。

class AccountComparator implements Comparator<BankAccount> { 

    @Override 
    public int compare(BankAccount o1, BankAccount o2) { 
     return o1.getName().compareTo(o2.getName()); 
    } 

} 

然後排序列表時,使用此自定義Comparator的一個實例:

Collections.sort(list, new AccountComparator()); 

或者更容易例如當你只需要做一次:

list.sort((a,b) -> a.getName().compareTo(b.getName()));