将列表数据放入地图时获取exception

我正在遍历一个列表,并将其内容放在地图上,但问题是,当我返回该地图时,我正在为一个exception提出exception,请你告诉它背后的原因是什么。我得到了java.lang.IndexOutOfBoundsException :索引:100,大小:100,因为我的列表大小是100

for(Map.Entry entries : result.entrySet()) { pairList.add(new Pair(entries.getKey(), entries.getValue())); } int sum = 0; int min = -1; int max = -1; int i = 0; Pair p = pairList.get(i); @SuppressWarnings("rawtypes") //Iterator iterator = pairList.iterator(); Iterator iterator = pairList.listIterator(); while (iterator.hasNext()) { if(sum == 0){ min = (int) p.key; max = (int) p.key; } sum += p.value; if(sum  BARRIER) { i--; } else { max = (int) p.key; } System.out.println(min+"_"+max); result1.put(min,max); sum = 0; } i++; p = pairList.get(i); } System.out.println("#########"); System.out.println(result1.size()); for (Map.Entry entry : result1.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); } 

伙计们请告知如何克服这一点

数组是零索引的。 例如,100个元素的数组实际上具有[0,99]的有效索引范围。 我假设这发生在p = pairList.get(i);

你需要实现一些逻辑,以确保你没有超越边界。 你已经在使用迭代器来迭代通过pairList ,这可以保护你免受这种情况的影响,但是你也混入了索引i ,这违背了迭代器的目的。

至少,在尝试访问元素之前包括一个检查。 就像是:

 if (i >= pairList.size()) break; 

你的问题在这里:

 p = pairList.get(i); 

如果列表大小为100,则允许的索引介于0到99之间。