Java 可比的接口问题



所以我有一个程序,它用数字方式对带有字符串和双精度的数组列表进行排序。我还必须按字母顺序对数组进行排序,而不使用包含 compareTo 代码的 BankAccount 类进行调整。

我只能修改包含在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);
    }
}

您可以实现一个自定义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()));

相关内容

  • 没有找到相关文章

最新更新