Java ArrayList越界异常?
我得到一个arraylist越界异常:索引4999,大小4999在此方法中:Java ArrayList越界异常?,java,exception,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 (co
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(int y=0;y
我不确定是什么原因导致了这种情况,我已经将for循环更改为包含一个ArrayList.size-1以适应这种情况,因为我知道它会发生,但它仍然会发生。trees 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;
}
treesAr=treeGen.generate(am);
Texture tex1=Main.assetManager.loadTexture(“Textures/Terrain/Trees/Trees1.png”);
BuffereImage trees=ImageToAwt.convert(tex1.getImage(),false,true,0);
公共ArrayList生成(整数金额){
ArrayList树=新的ArrayList();
几何图形树=(几何图形)Main.assetManager.loadModel(
“模型和纹理/景观/树木/松树.obj”);
对于(int i=0;i
这样做的目的是加载一个图像,检查图像中是否有绿色像素,并创建一个包含代表每个像素位置的矢量的arraylist
然后加载树,并通过for循环检查树的随机位置。如果树位于像素区域内,则将它们添加到场景中,否则不会发生任何事情
这允许我绘制一个图像并绘制出允许树繁殖的位置。for(int x=0;x for (int x = 0; x < treePosB.size() - 1; ++i) {
您键入此循环时出错(
x
->i
)。它无限地增加i
,直到超过列表的大小。@TastyLemons你是想键入++x
;而不是键入++i
。我太笨了。有时,当我从其他for循环复制粘贴时……非常感谢:)@TastyLemons确保将此答案标记为已接受(单击数字下方的复选标记)让其他人知道问题已经得到了回答。还要等1分钟:P