如何仅使用对象的属性获取ArrayList中对象的索引?

时间:2015-02-02 01:03:16

标签: java object indexing arraylist

这是ArrayList类,我试图通过仅使用帐号来获取Account对象的索引。我的帐户对象包含((object)Customer, (double) Balance),我的客户对象包含((object) Name, (String) actNum, (object) Address)

import java.util.ArrayList;

public class Database {

    //Instance Veriables
    private ArrayList<Account> list;  
    private Account account;
    private int index;
    private Boolean found;


    public Database()
    {
        list = new ArrayList<Account>();
    }

    public void addAccount(Account a)
    {
        list.add(a);
    }

    public void deleteAccount(int i)
    {
        list.remove(i);
    }

    public void searchAccount(String actNum)
    {

        this.found = list.contains(actNum);
        this.index = list.indexOf(actNum);
        this.account = list.get(0);
    }

    public int getIndex()
    {
        return index;
    }

    public Account getAccount()
    {
        return account;
    }

    public Boolean isInList()
    {
        return found;
    }

}

1 个答案:

答案 0 :(得分:0)

private int indexForAccountWithNum(String searchActNum) {
    for (int i = 0; i < list.size(); i++)
        if (list.get(i).getCustomer().getAccountNum() == searchActNum)
            return i;
    return -1;
}

或者在Java 8中

IntStream.range(0, list.size())
    .filter(i -> list.get(i).getCustomer().getAccountNum() == searchActNum)
    .findFirst().orElse(-1);