Java ArrayList 中的索引越界异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6563693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:47:05  来源:igfitidea点击:

index out of bounds exception in ArrayList

javafor-looparraylist

提问by Andrew delgadillo

Here is the error message I get:

这是我收到的错误消息:

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    at java.util.ArrayList.get(ArrayList.java:322)
    at pie.chart.explorer.alpha.ShowPieChart.<init>(ShowPieChart.java:28)
    at pie.chart.explorer.alpha.PieChartMain.jButton2ActionPerformed(PieChartMain.java:101)
    at pie.chart.explorer.alpha.PieChartMain.access0(PieChartMain.java:22)
    at pie.chart.explorer.alpha.PieChartMain.actionPerformed(PieChartMain.java:63)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6267)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
    at java.awt.Component.processEvent(Component.java:6032)
    at java.awt.Container.processEvent(Container.java:2041)
    at java.awt.Component.dispatchEventImpl(Component.java:4630)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
    at java.awt.Container.dispatchEventImpl(Container.java:2085)
    at java.awt.Window.dispatchEventImpl(Window.java:2478)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
BUILD SUCCESSFUL (total time: 14 seconds)

And here is the code:

这是代码:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pie.chart.explorer.alpha;

import java.awt.Color;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JFrame;

/**
 *
 * @author Andrew
 */
public class ShowPieChart extends JFrame {

    PiePanel pieChart;

    public ShowPieChart(ArrayList<Float> val, ArrayList<Color> col) {
        super("Pie Chart");
        int index = 1;
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        FlowLayout flow = new FlowLayout();
        pieChart = new PiePanel(val.size());
        for(Iterator<Float> i = val.iterator(); i.hasNext(); )  {
         pieChart.addSlice(col.get(index), val.get(index));
         index++;
        }
        setLayout(flow);
        add(pieChart);
        setVisible(true);
    }
}

I have tried lots of things to fix this problem, but I can't tell why I still keep getting an IndexOutOfBoundsException. To the best of my knowledge, I am pretty sure this is correct! Can you help?

我已经尝试了很多方法来解决这个问题,但我不知道为什么我仍然不断收到 IndexOutOfBoundsException。据我所知,我很确定这是正确的!你能帮我吗?

回答by Jiri Kriz

Index intialization should be:

索引初始化应该是:

int index = 0;

Because the values of the index are between 0 and lenght-1

因为索引的值在 0 到 lenght-1

回答by Mahesh

indexvariable should start from 0. If the size of the array is nthen it's index starts from 0to n-1.

index变量应该从 0 开始。如果数组的大小是n那么它的索引从0开始到n-1

回答by Eternal_Light

index should be initialised as 0.

索引应初始化为 0。

回答by mcgarveymr

The exception is showing that you are trying to access index 2, but the list is only of size 2. Initialize your index variable to 0, as list indexes (like array indexes) start with 0 and run up to size()-1.

异常显示您正在尝试访问索引 2,但列表的大小仅为 2。将索引变量初始化为 0,因为列表索引(如数组索引)从 0 开始并运行到size()-1

回答by Giulio Piancastelli

The smallest change that would let you run the code without exceptions is, as others have already pointed out, setting indexat 0. But I would also completely rewrite your forloop, in what I think is a better coding style.

这将让最小化运行没有异常的代码,因为其他人已经指出的那样,设置index0。但我也会完全重写你的for循环,我认为这是一种更好的编码风格。

int dataSize = val.size();
pieChart = new PiePanel(dataSize);
for (int i = 0; i < dataSize; i++) {
    pieChart.addSlice(col.get(i), val.get(i));
}

You don't need to use an Iterator, since you never access it inside the forloop. Better use a numeric index instead, which you can introduce inside the fordefinition and have it automatically incremented at each pass through the loop.

您不需要使用 an Iterator,因为您永远不会在for循环内访问它。最好使用数字索引,您可以在for定义中引入它,并在每次循环时自动递增。

回答by Konrad Rudolph

In addition to what the others have said, you nowhere increment your iterator:

除了其他人所说的,你无处增加你的迭代器:

for (Iterator<Float> i = val.iterator(); i.hasNext(); ) {
    pieChart.addSlice(col.get(index), val.get(index));
    index++;
}

You need to do the following, otherwise this loop will never terminate.

您需要执行以下操作,否则此循环将永远不会终止。

for (Iterator<Float> i = val.iterator(); i.hasNext(); i.next()) …

But it's not clear what you need this iterator for anyway.

但是不清楚你需要这个迭代器做什么。