gpt4 book ai didi

java - 如何遍历自定义列表?

转载 作者:搜寻专家 更新时间:2023-11-01 08:21:07 25 4
gpt4 key购买 nike

我有这种平静的代码,想知道如何通过遍历它来使它更优雅。试图将列表和适配器放在一个对象数组中,但我无法用它调用 .size()

从这里开始:

int breakfastIndex = //get index.
if(breakfastIndex != -1 && breakfastFoodList.size() > breakfastIndex) {
breakfastFoodList.remove(breakfastIndex);
breakfastAdapter.notifyItemRemoved(breakfastIndex);
}

int lunchIndex = intent.getIntExtra("position", -1);
if(lunchIndex != -1 && lunchFoodList.size() > lunchIndex) {
lunchFoodList.remove(lunchIndex);
lunchAdapter.notifyItemRemoved(lunchIndex);
}

int dinnerIndex = intent.getIntExtra("position", -1);
if(dinnerIndex != -1 && dinnerFoodList.size() > dinnerIndex) {
dinnerFoodList.remove(dinnerIndex);
dinnerAdapter.notifyItemRemoved(dinnerIndex);
}

int snackIndex = intent.getIntExtra("position", -1);
if(snackIndex != -1 && snackFoodList.size() > snackIndex) {
snackFoodList.remove(snackIndex);
snackAdapter.notifyItemRemoved(snackIndex);
}

对此:

for(int i = 0; i < 4; i++) {
int index = //get index.
if(index != -1 && foodList[i].size() > index) {
foodList[i].remove(index);
adapter[i].notifyItemRemoved(index);
}
}

最佳答案

你可以做两个数组

List[] lists = {breakfastFoodList,...};
ArrayAdapter[] adapters = {breakfastAdapter,...};

那么,您编写的循环看起来没问题。

但是,如果您尝试一次删除所有膳食,我觉得您应该存储一个列表,然后导出其余的

例如,

public class DailyMeal {
Meal breakfast, lunch, dinner, snack;
}

然后,对于你的列表

// In the Activity 
private List<DailyMeal> meals;
public List<Meal> getBreakfasts(); // return list of all breakfasts
public List<Meal> getLunches();
// etc.

当您从膳食列表中删除 DailyMeal 对象时,您会自动删除该“日期”的每个 Meal 对象

关于java - 如何遍历自定义列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50893784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com