简体   繁体   English

尝试使用基于 1 的索引创建 ArrayList 的索引越界异常

[英]Index out of bounds exception trying to create ArrayList with 1-based indices

So up until this point I've just used points.add(new Point(x,y)) to add points to my ArrayList .所以到目前为止,我只是使用points.add(new Point(x,y))将点添加到我的ArrayList However, I found out that I need the first point to be in index=1 in order to make it possible to multiply the number for each step.但是,我发现我需要第一个点在 index=1 中,以便可以将每个步骤的数字相乘。 So I tried setting the counter from 0 to 1 , and as expected I knew I would get a error because of the range, but I've tried changing up the condition within the while-loop, but nothing seems to work.所以我尝试将counter0设置为1 ,正如预期的那样,我知道我会因为范围而出错,但是我尝试在 while 循环中更改条件,但似乎没有任何效果。

Here's my code:这是我的代码:

ArrayList<Point> points = new ArrayList<>();
int counter = 1;
int nPoints = 12;
while (counter <= nPoints) {
    x = (int) (centerX + r * Math.cos(start));
    y = (int) (centerY + r * Math.sin(start));

    points.set(counter, (new Point(x, y)));
    //points.add(new Point(x,y));

    counter++;
}

This is the error that I am getting:这是我得到的错误:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0   
    at java.util.ArrayList.rangeCheck(Unknown Source)   
    at java.util.ArrayList.set(Unknown Source)

I've deleted much of the code that isn't relevant for this problem in order to make it easier to read.为了更容易阅读,我删除了与此问题无关的大部分代码。

Edit:编辑:

 public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            a = getWidth() /2;
            b = getHeight() /2;
            g2d.setColor(Color.RED);

            //draw cirle
            g2d.drawOval(a-r, b-r, 2*r, 2*r);

            //draw lines
            for (int  i= 1; i < points.size();i ++) {
                g2d.drawLine(points.get(i).x, points.get(i).y, points.get(i+1).x, points.get(i+1).y);

            }

           g2d.dispose();
        }

I've created a circle in which I'm trying to draw lines between points along the circumference.我创建了一个圆,我试图在其中沿着圆周在点之间画线。 Here I want the 1st point to connect to 2, 2 to 4, 3 to 6, 4 to 8 and so on... So the pattern here is is that it is multiplied by 2 for each time.这里我希望第一个点连接到 2、2 到 4、3 到 6、4 到 8 等等......所以这里的模式是每次乘以 2。 So my initial thought was that I could use the i inside the for -loop to multiply by 2 each time.所以我最初的想法是我可以使用for循环中的i每次乘以 2。 But since I have my first point in i=0 inside the ArrayList, I am having trouble.但是由于我在 ArrayList 中的 i=0 中有我的第一个点,所以我遇到了麻烦。

Your trying to set an index that doesn't exist.您试图设置一个不存在的index

The size of your ArrayList is 0 but you are trying to access index 1 which doesn't exist.您的ArrayList的大小为 0,但您正在尝试访问不存在的索引1

You can use ArrayList.add() to add another element to your ArrayList .您可以使用ArrayList.add()将另一个元素添加到您的ArrayList If you use set() the index must actually exist in the ArrayList .如果您使用set() index必须实际存在于ArrayList

To insert an element at index 0 use points.add(null);要在索引0处插入元素,请使用points.add(null); before loop.循环前。

So the final code looks like:所以最终的代码看起来像:

ArrayList<Point> points = new ArrayList<>();
int counter = 1;
int nPoints = 12;
points.add(null); // <= this line was added
while (counter <= nPoints) {
    x = (int) (centerX + r * Math.cos(start));
    y = (int) (centerY + r * Math.sin(start));

    //points.set(counter, (new Point(x, y))); // <= it's not correct use
    points.add(new Point(x,y));

    counter++;
}

Use add instead of set .使用add而不是set You can not set (replace) an item that does not exist.您不能设置(替换)不存在的项目。 From the docs on set :从在文档set

Replaces the element at the specified position in this list with the specified element.用指定的元素替换此列表中指定位置的元素。

You can use index + 1 for your calulations, but list indices should start at 0.您可以使用index + 1进行计算,但列表索引应从 0 开始。

Edit:编辑:

//draw lines
for (int  i= 0; i < points.size() - 1;i ++){
    g2d.drawLine(points.get(i).x,
    points.get(i).y, points.get(i+1).x,
    points.get(i+1).y);
}

ArrayList s in Java do not extend to the desired length if you try to set a value outside of it's range.如果您尝试设置超出范围的值,Java 中的ArrayList不会扩展到所需的长度。 You are trying to set item at index 1, when the array has 0 length.当数组的长度为 0 时,您正试图在索引 1 处设置 item。 Try this:尝试这个:

ArrayList<Point> points = new ArrayList<>();
points.add(null);
for (int counter = 0; counter < nPoints; counter++) {
    x = (int) (centerX + r * Math.cos(start));
    y = (int) (centerY + r * Math.sin(start));

    points.add(new Point(x,y));
}
points.set(0, points.get(1));

EDIT: you are generating the same Point nPoints times.编辑:您正在生成相同的Point nPoints 次。 Do something with the angle, for example:用角度做一些事情,例如:

x = (int) (centerX + r * Math.cos(start + counter * 0.01));
y = (int) (centerY + r * Math.sin(start + counter * 0.01));

EDIT: replacing the 0th element with the 1st编辑:用第一个元素替换第 0 个元素

EDIT: now that you provided the paint code, I see that your algorithm does not necessarily use 1-based indices.编辑:既然您提供了绘制代码,我发现您的算法不一定使用基于 1 的索引。 By the way I highly doubt that you got a null point out of the list.顺便说一句,我非常怀疑您是否从列表中获得了零点。 I suspect that even your list is not saved, and got null pointer exception on the list, not on the point.我怀疑即使您的列表也没有保存,并且列表上出现空指针异常,而不是重点。 Anyway, try this:无论如何,试试这个:

ArrayList<Point> points = new ArrayList<>();
for (int counter = 0; counter < nPoints; counter++) {
    x = (int) (centerX + r * Math.cos(start));
    y = (int) (centerY + r * Math.sin(start));

    points.add(new Point(x,y));
}

// ...

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    a = getWidth() /2;
    b = getHeight() /2;
    g2d.setColor(Color.RED);

    //draw cirle
    g2d.drawOval(a-r, b-r, 2*r, 2*r);

    //draw lines
    for (int  i= 1; i < points.size();i ++) {
        g2d.drawLine(points.get(i - 1).x, points.get(i - 1).y, points.get(i).x, points.get(i).y);
    }

    g2d.dispose();
}

In my case that helped:就我而言,这有帮助:

if (!listName.isEmpty()) {
            return listName.get(0);
        }

Hope it works by you ☺️希望它对你有用☺️

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM