2016-03-06 55 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()));