【问题标题】:Remove Object from ArrayList based on User Input根据用户输入从 ArrayList 中删除对象
【发布时间】:2014-02-06 12:37:06
【问题描述】:

我有一个看起来像这样的对象:

Account account = new Account (0, fName, sName, adr, city, pos, uniqueID);

然后我通过用户输入将该对象放入 ArrayList:

List<Account> newAcc = new ArrayList<Account>();

这就是问题所在。我需要一种巧妙的方法来根据用户输入删除该对象。这是我尝试过的:

System.out.print("1. Client with Accounts.\n2. Client with Savings Accounts.\n3. Remove all Accounts.\n");
int inputRmv = in.nextInt();

case 1:
    for (Iterator i = newAcc.iterator(); i.hasNext(); ) {
        if (i.equals(rmvID)) {
            newAcc.remove(i);

这不起作用。对象不会以这种方式被移除。

基本上:有没有办法使用用户输入,然后遍历列表以查看是否有任何对象包含与该对象的任何部分等效的字符串?

我急需,因此非常感谢任何帮助我朝正确方向前进的帮助!

干杯。

【问题讨论】:

  • 在第一篇文章中引用了错误的数组,对不起。

标签: java object arraylist iterator


【解决方案1】:

您将Iterator 对象与rmvId 进行比较。这将始终返回false,因为它们不是同一个type。我猜你想检查迭代器的下一个对象的 id 是否等于rmvId

所以使用i.next() 获取下一个SavingsAccount,将其id 与rmvId 进行比较,然后通过Iterator 将其删除。

  SavingsAccount sa = i.next();
  if (sa.getId().equals(rmvID)) { // just an example.. I don't know how you access the 
                                  // saving account's id nor it's type. This example expect
                                  // it is `Integer`
     i.remove();
  }

如果SavingsAccount id 是int 类型,您可以这样比较sa.getId() == rmvID

【讨论】:

  • 另外,确保Account 覆盖equals()(和hashCode())。
【解决方案2】:

检查 objects 属性是否包含给定的 id ,然后通过其索引删除列表中的相关对象

for(int i=0;i<newSacc.size();i++){
    if (newSacc.get(i).getId().equals(rmvID)){
        newSacc.remove(i);
    }
}

【讨论】:

  • 哦,您应该从列表末尾循环以从列表中删除任何内容。否则,使用列表 [1, 1, 1, 1, 1],从列表中删除 1 而不是空列表后,您将得到 [1, 1]。
猜你喜欢
  • 2017-02-28
  • 1970-01-01
  • 2012-10-30
  • 2019-04-08
  • 2021-03-11
  • 2015-08-02
  • 2017-01-11
相关资源
最近更新 更多