简体   繁体   English

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

[英]How do I get the index of an object in an ArrayList using only a property of the object?

This is the ArrayList class, I am trying to get the index of the Account object by using only an Account Number. 这是ArrayList类,我试图仅使用一个帐号来获取Account对象的索引。 My Account Object consists of ((object)Customer, (double) Balance) and my Customer Object consists of ((object) Name, (String) actNum, (object) Address) . 我的客户对象由((object)Customer, (double) Balance)组成,而我的Customer Object由((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;
    }

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

Or in Java 8 或在Java 8中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM