我在menuItemArrayList中提供产品,当用户将他们选择的产品放在购物车中时,它们将被添加到selectionItemArrayList中。下面是我的代码,它检查购物车中是否已经存在该产品。如果是这样,那么只更新数量。
我一直在摆弄代码,但我一直收到这个错误
IndexOutOfBoundsException: Index: 0, Size: 0
代码只是从回收器视图的onBindHolder中摘录的一段onClickListener:
int position = getAdapterPosition();
for (int j = 0; j <= selectionItemArrayList.size(); j++) {
if (menuItemArrayList.get(position).getMenuItemName().equals(selectionItemArrayList.get(j).selectionName)) { // Loop through selection array to see if item exists in array
selectionItemArrayList.get(j).selectionQuantity += 1; // if it does exist then only update the quantity by 1
} else {
// Get the item name, price and add 1 to the quantity
String menuItemName = menuItemArrayList.get(position).getMenuItemName();
String menuItemPrice = menuItemArrayList.get(position).getMenuItemPrice();
SelectionItem selectionItems = new SelectionItem(menuItemName, menuItemPrice, 1);
selectionItemArrayList.add(selectionItems);
}
}
你知道我做错了什么吗?在将主数组中的产品名称与购物车数组中的产品名称进行比较的行上抛出异常。
发布于 2019-05-21 03:05:32
这是你的循环:
(int j= 0;j <= selectionItemArrayList.size();j++)
在遍历列表时,您几乎总是希望使用<
,而不是<=
。这是因为列表索引从0开始。因此,大小为2的列表具有0和1的项。
当您在包含零个元素的列表上使用<=
时,它仍将尝试访问索引为0的元素(因为0为<=
0)。但是您的列表是空的;它在索引0处没有元素。所以你崩溃了。
试着这样做:
for (int j = 0; j < selectionItemArrayList.size(); j++)
https://stackoverflow.com/questions/56226685
复制相似问题