簡體   English   中英

通過迭代器從 ArrayList 中刪除一個對象

[英]Delete an object from ArrayList by iterator

我想創建一個類似於家庭預算的程序,所以我有一個AmountModel類(我知道Integer對 id 不太好,但現在不是問題):

import java.time.LocalDate;

public class AmountModel {
  private Integer id;
  private Double amount;
  private CategoryModel categoryModel;
  private LocalDate localDate;

  // getters/setters etc.
}

在另一個類中,我構建了這個deleteAmount方法:

static Scanner sc = new Scanner(System.in);

public List<amountModel> deleteAmount() {
    Iterator<AmountModel> it = amountList.iterator();
    while (it.hasNext()) { 
        System.out.println("Choose index to delete ");
        AmountModel am = it.next();
        if (am.getId().equals(sc.nextInt())) {
            it.remove();
        }
        break;
    }
    return amountList;
}

添加對象效果很好,但是當我嘗試使用刪除方法時,我必須將第一個索引。

例子:
我有三個對象(索引為 0、1、2)。

  • 當我選擇 1 或 2 程序時,什么都不做。
  • 當我選擇 0 程序刪除第一個索引時,保留索引 1 和 2。
  • 當我選擇 2 時,程序什么也不做。
  • 當我選擇 1 時,程序刪除索引 1,保留索引 2...等等。

這種方法有什么問題?

您應該將輸入邏輯與刪除邏輯分開,並接受列表作為參數。

注意:這只適用於可變列表。 如果你使用像 Arrays.asList() 這樣的東西,它會拋出一個異常。

public void deleteAmount(List<AmountModel> list, int key) {
    list.removeIf(a -> a.getId().equals(key));
}

歡迎使用堆棧溢出!

正如其他人所提到的,有幾種方法可以解決這個問題。 但我認為您可以通過更改用於訪問您的AmountModel集合的數據結構使這更簡單:如果您經常通過 ID 訪問項目,則Map非常適合。

不再擔心迭代器狀態; 你可以這樣做:

// Map "amounts" by ID for easy O(1) lookup.
static Map<Integer, AmountModel> amountMap

public void deleteAmount(Integer id) {
  if (!amountMap.containsKey(id)) { 
    // (TODO: Handle invalid input)
    throw new Exception()
  }

  amountMap.remove(id)
  return
}

希望這可以幫助! 如果您有興趣,我在這里匯總了一個工作示例。 (在 Groovy 中,但應該足以給你這個想法)

您的 break 語句僅在第一次迭代中中斷 while 循環。 因此,只有當第一個 am.getId() 與您的第一個輸入匹配時,它才會起作用。 此外,您的 sc.nextInt() 將繼續掃描下一個可用輸入,將其從 while 循環中刪除。

static Scanner sc = new Scanner(System.in);
public List<AmoutModel> deleteAmount() {
    Iterator<AmoutModel> it = amountList.iterator();
    Integer scId = sc.nextInt();
    while (it.hasNext()) { 
        System.out.println("Choose index to delete ");
        AmoutModel am = it.next();
        if (am.getId().equals(scId)) {
            it.remove();
            break;
        }
    }
    return amountList;
}

在循環外調用 sc.nextInt() ,否則每次循環返回時它都會運行,因為每次循環結束時都會重新評估條件。 你也可以使用列表的刪除方法

    static Scanner sc = new Scanner(System.in);
    public List<AmoutModel> deleteAmount() {
        System.out.println("Choose index to delete ");
        int index = sc.nextInt();
        amountList.remove(index);
        return amountList;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM