如何搜索对象的ArrayList

时间:2018-02-28 02:12:52

标签: java arraylist contains

我正在创建一个Account s(一个对象)的ArrayList,而Account构造函数是

public Account(String name, int accNum, int balance)
{
    myName = name;
    myAccountNum = accNum;
    myBalance = balance;
}

我想知道如何检查ArrayList以确定其中是否存在给定的accountNumber,如果存在,return true

private static ArrayList<Account> accounts = new ArrayList<Account>();

我最初的想法是这样,但我认为这不起作用

if(accounts.contains(tempAccNum))
{
    //executes code that I have
}

3 个答案:

答案 0 :(得分:0)

对于Java ArrayListcontains执行对象相等性比较。要使用.contains,您需要

  1. 为Account类实施.equals()方法,并让它仅根据输入this.myAccountNum的帐号检查Account属性。
  2. 使用所需的帐号创建一个虚拟Account以传递到contains
  3. 更好的方法是评估迭代器,并检查每一步的帐号。在这里,我假设myAccountNumAccount类的公共属性。

    Iterator<E> it = Accounts.iterator();
    while (it.hasNext()) {
        Account acc = it.next();
        if(acc.myAccountNum == tempAccNum)
            return true;
    }
    

    对于ArrayList具体来说,使用带有索引的.get并不算太糟糕:

    for(int index = 0; index < Accounts.size(); ++index) {
        if(Accounts.get(index).myAccountNum == tempAccNum)
            return true;
    

    对于其他List类型,使用索引可能非常差 Ways to iterate over a list in Java

答案 1 :(得分:0)

我建议您通过为帐户类实施equals()方法来简化。

@Override
public boolean equals(Object o){
  if(o==null)return false;
  if(o.getClass()!=this.getClass())return false;
  Account demo = (Account)o;
  if(!demo.myName.equals(this.myName))return false;
  if(demo.myAccountNum != this.myAccountNum)return false ;
  if(demo.myBalance = this.myBalance)return false ;
}

然后使用contains方法

答案 2 :(得分:0)

首先在accNum模型中添加Account的getter

然后试试这个

public boolean containsAcc(int accno) {
    for(int i=0;i<accounts.size();i++) {
        if(accounts!= null && accounts.get(i).getMyAccountNum()==acno) {
            return true;
        }
    }
    return false;
}

此处getMyAccountNum()Account模型中声明的getter(如下所示)

然后检查

if(containsAcc(tempAccNum))
{
//your code
}

您的帐户模型应该是这样的

public class Account {
String myName;
int myAccountNum;
int myBalance;
public Account(String name, int accNum, int balance)
{
    this.myName = name;
    this.myAccountNum = accNum;
    this.myBalance = balance;
}

public int getMyAccountNum() {
    return myAccountNum;
}
}
相关问题