gpt4 book ai didi

java - 如何解决Android中的Array IndexOutOfBoundException

转载 作者:行者123 更新时间:2023-12-01 04:45:58 25 4
gpt4 key购买 nike

我有 5 个年份列表和 5 个与年份列表相对应的金额列表。

year_Earnings = [2011,2012,2013];
year_Expense = [2011,2012];
year_Investment = [2013];
year_Returns=[];
year_Savings=[2011,2012,2013];


amount_Earnings = [10,20,7];
amount_Expense = [5,10];
amount_Investment = [5];
amount_Returns=[];
amount_Savings=[5,10,7];

显然,当我尝试在单个 for 循环中迭代所有列表时,我会得到 ArrayIndexOutOfBoundException。所以我使用下面的代码将所有列表转换为带有键值对的 HashMap

 Map<Double, Double> earningsMap = listToMap(year_Earnings, amount_Earnings);
Map<Double, Double> expensesMap = listToMap(year_Expense, amount_Expense);
Map<Double, Double> investmentMap = listToMap(year_Investment, amount_Investment);
Map<Double, Double> returnsMap = listToMap(year_Returns, amount_Returns);
Map<Double, Double> savingsMap = listToMap(year_Savings, amount_Savings);



public Map<Double, Double> listToMap(List<Double> years, List<Double> money) {
Map<Double, Double> newMap = new HashMap<Double, Double>();
if (years == null || money == null || years.size() != money.size()) {
throw new IllegalArgumentException();
}
for (int i=0; i< years.size(); i++ ) {
newMap.put(years.get(i), money.get(i));
}

return newMap;
}

现在我想要如下所示的列表

year_Earnings = [2011,2012,2013];
year_Expense = [2011,2012,2013];
year_Investment = [2011,2012,2013];
year_Returns=[2011,2012,2013];
year_Savings=[2011,2012,2013];


amount_Earnings = [10,20,7];
amount_Expense = [5,10,0];
amount_Investment = [0,0,5];
amount_Returns=[0,0,0];
amount_Savings=[5,10,7];

任何人都可以帮我做这件事吗..提前谢谢你

最佳答案

I have 5 lists of years and 5 lists of amounts corresponding to year lists.

=> 这是一个糟糕的解决方案,因为如果你遵循这个,那么你必须管理 10 个列表,相反,我建议你创建 Only Single ArrayList<Object> ,每个项目都是对象类型。

1) 使用 getter/setter 方法定义一类 Earnings。

public class Earning {

int year;
int amount;

public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}

2) 定义ArrayList<Earning>类型,随时创建 Earnings 类型的对象并将其放入 ArrayList 中。

关于java - 如何解决Android中的Array IndexOutOfBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15830609/

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