【问题标题】:How do I get the index of an object in an ArrayList using only a property of the object?如何仅使用对象的属性获取 ArrayList 中对象的索引?
【发布时间】:2015-02-02 01:03:15
【问题描述】:

这是 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;
    }

}

【问题讨论】:

    标签: java object indexing arraylist


    【解决方案1】:
    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);
    

    【讨论】:

    • 问题是 accountNum 甚至不在 Account 类中,它在另一个名为 Customer 的子类中。所以它就像是深层次的类,它不断收到错误
    • 我添加了一个 getCustomer 调用。如果您遇到错误,您需要发布错误以及触发它们的代码的任何详细信息。
    • @DavidSchiumerini 你应该accept 答案。
    猜你喜欢
    • 2020-03-02
    • 2014-01-17
    • 2014-12-24
    • 1970-01-01
    • 2012-01-05
    • 2016-08-20
    • 2020-02-02
    • 2011-04-09
    • 2011-11-02
    相关资源
    最近更新 更多