对对象的ArrayList进行排序? [英] Sort an ArrayList of objects?

查看:320
本文介绍了对对象的ArrayList进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助如何对对象的ArrayList进行排序。我有超类帐户和两个子类SavingsAccount和CreditAccount。在Account类中,当我想知道帐号时,我有这个方法来调用:

I need some help how to sort an ArrayList of objects. I have the superclass Account and two subclasses SavingsAccount and CreditAccount. Inside the Account class I have this method to call when I want to know the account number:

// Get account number
public String getAccountNumber() {
    return accountNumber;
}

我需要对帐号进行排序,以获得所有帐号中的最高帐号对象?

I need to sort the account numbers to get the highest number of all accounts in the objects?

ArrayList是这样的:

The ArrayList is like this:

ArrayList<Account> accountList = new ArrayList<Account>();

这可以用简单而不复杂的方式完成吗?谢谢!

Could this be done in a simple and not to comlicated way? Thanks!

推荐答案

首先,为什么帐户号码被表示为字符串?它是一个数字,还是文本?无论如何,绝对可以使用 Collections.sort

For a start, why is an account number being represented as a string? Is it a number, or is it text? Anyway, it's absolutely possible to sort your list using Collections.sort:

Collections.sort(list, new Comparator<Account>() {
    @Override public int compare(Account x, Account y) {
        return x.getAccountNumber().compareTo(y.getAccountNumber();
    }
});

如果它为你排序错误(升序而不是降序),则反转比较:

If that sorts them in the wrong sense for you (ascending instead of descending), reverse the comparison:

Collections.sort(list, new Comparator<Account>() {
    @Override public int compare(Account x, Account y) {
        return y.getAccountNumber().compareTo(x.getAccountNumber();
    }
});

请注意,由于这些是字符串,因此会按字典顺序对它们进行排序如果您使用的是数字,那就是不会有问题。

Note that as these are strings, it will sort them in lexicographic order. If you were using numbers instead, that wouldn't be a problem.

在这种情况下我不会推荐的另一种方法是使帐户实施可比较<帐户> 。当有一种比较两个账户的自然方式时,这是合适的 - 但我可以看到你有时可能希望按号码排序,有时候是通过账户持有人的名字排序,有时候是通过账户中的资金,有时是按日期排序该帐户已创建等。

An alternative which I wouldn't recommend in this case is to make Account implement Comparable<Account>. That's suitable when there's a single "natural" way of comparing two accounts - but I can see that you might want to sometimes sort by number, sometimes by the name of the account holder, sometimes by the funds within the account, sometimes by the date the account was created etc.

顺便说一句,目前尚不清楚真的需要对此进行排序 - 如果您只需需要找到最大的帐号,您不需要对其进行排序,您只需要迭代并记住最大数量的帐户:

As an aside, it's not clear that you really need to sort this at all - if you just need to find the largest account number, you don't need to sort it, you just need to iterate and remember the account with the largest number as you go:

Account maxAccount = null;
for (Account account : accounts) {
    if (maxAccount == null || 
        account.getAccountNumber().compareTo(maxAccount.getAccountNumber()) > 0) {
        maxAccount = account;
    }
}

这篇关于对对象的ArrayList进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆