java - ArrayList越界异常?

标签 java exception arraylist

我在这个方法中遇到了 arraylist 越界异常:索引 4999,大小 4999:

for (int y = 0; y < trees.getHeight() - 1; ++y) {
        for (int x = 0; x < trees.getWidth() - 1; ++x) {
            int c = trees.getRGB(x, y);
            Color color = new Color(c);
            if (color.getRed() == 0 && color.getGreen() == 255 && color.getBlue() == 0) {
                treePosB.add(new Vector2f(x, y));
            }
        }
    }

    int randX = 0;
    int randZ = 0;
    boolean canPlace = false;
    for (int i = 0; i < treesAr.size() - 1; ++i) {
        randX = randInt(-terrain.getTerrainSize(), terrain.getTerrainSize());
        randZ = randInt(-terrain.getTerrainSize(), terrain.getTerrainSize());
        treesAr.get(i).setLocalTranslation(randX, terrain.getHeight(new Vector2f(randX, randZ)) - (40 + 1.0f), randZ);

        for (int x = 0; x < treePosB.size() - 1; ++i) {
       //FOLLOWING LINE CAUSES ERROR
            if (treesAr.get(i).getLocalTranslation().x == treePosB.get(x).x && treesAr.get(i).getLocalTranslation().y == treePosB.get(x).y) {
                canPlace = true;
                continue;
            }
        }
        if (canPlace) {
            treeNode.attachChild(treesAr.get(i));
        } else {
        }
    }

我不确定是什么导致了这种情况,我已经更改了 for 循环以包含 ArrayList.size - 1 来对此进行调整,因为我知道它会发生,但它仍然发生。树 ArrayLIst 的创建方式如下:

    treesAr = treeGen.generate(am);

    Texture tex1 = Main.assetManager.loadTexture("Textures/Terrain/Trees/Trees1.png");
    BufferedImage trees = ImageToAwt.convert(tex1.getImage(), false, true, 0);

    public ArrayList<Geometry> generate(int amount) {
    ArrayList trees = new ArrayList();
    Geometry tree = (Geometry) Main.assetManager.loadModel(
            "Models and Textures/Landscape/Trees/Pine.obj");
    for (int i = 0; i < amount - 1; ++i) {
        Geometry treeI = tree.clone();
        trees.add(treeI);
    }
    return trees;
}

它的作用是加载图像,检查图像中的绿色像素,并使用代表每个像素位置的 vector 创建一个数组列表。

然后加载树,并通过 for 循环并检查树的随机位置。如果树在像素区域内,它们就会被添加到场景中,否则什么也不会发生。

这允许我绘制图像并画出允许树木生成的位置。

最佳答案

    for (int x = 0; x < treePosB.size() - 1; ++i) {

您错误输入了此循环 (x -> i)。它无限增加i,直到超过列表的大小。

关于java - ArrayList越界异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21641910/

相关文章:

java - 打印字符串中使字符串与正则表达式匹配的部分

java - 通过/返回不起作用

Objective-C 堆栈跟踪

java - 在不同的数组中过滤一个 Arraylist

Java将ArrayList中的String转换为int时出错

java - 我的 Jacoco 报告显示代码覆盖率非常低

java - 比较两个文件中的每一行

.net - 从 VS2010 升级到 VS2012 后,Linq to EF Join 抛出 "Index was out of range"

java - 为什么 Integer.parseInt 在没有 try catch 的情况下进行编译?

c# - 从不同的 arraylist 索引添加到 arraylist