David Schiumerini
David Schiumerini

Reputation: 1

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. My Account Object consists of ((object)Customer, (double) Balance) and my Customer Object consists of ((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;
    }

}

Upvotes: 0

Views: 8875

Answers (1)

sprinter
sprinter

Reputation: 27996

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

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

Upvotes: 2

Related Questions