我想对此类项目进行排序(所有大写字母均排在首位):

A
B
C
D
a
b
c
d


如何使用集合排序?假设我的对象是Account,而accountName是我想要以这种方式排序的字段

谢谢

最佳答案

您需要在帐户类中实现Comparable接口,并重写compareTo()方法。

class Account implements Comparable{

    public String accountName;

    public Account(String accountName) {
        this.accountName = accountName;
    }

    public String getAccountName() {
        return accountName;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

    @Override
    public String toString() {
        return "Account [accountName=" + accountName + "]";
    }

    @Override
    public int compareTo(Object obj) {
        Account accObj = (Account) obj;

        return this.accountName.compareTo(accObj.accountName);
    }

}


现在Collections.sort()将返回您想要的结果。

List<Account> accList= new ArrayList<Account>();
accList.add(new Account("B"));
accList.add(new Account("c"));
accList.add(new Account("A"));

accList.add(new Account("C"));
accList.add(new Account("a"));
accList.add(new Account("b"));

Collections.sort(accList);

08-17 11:37