我正在尝试制作基于磁贴的游戏。我制作了一个Tile
课程,并为每个人提供了Rectangle
用于碰撞的课程。一旦我渲染并更新它们,我将它们全部存储到ArrayList
中。那部分工作正常,但是当我尝试通过getter从另一个类访问同一个ArrayList
时,我没有得到任何元素。我用我的控制台检查大小,它给了我正确的数字,但是当我尝试实际获得一个元素时
即rect.get(0)
,我收到了这些错误:
Exception in thread "Thread-3" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
我认为这是一个线程安全问题,但我已经尝试了使用synchronize
关键字到Collections
所能想到的一切,但没有运气。任何帮助都会非常感激。
使用代码编辑。很抱歉没有提前发布
public class Launcher extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 1500;
private static final int HEIGHT = 900;
private static final String title = ("Game Alpha");
volatile boolean running;
Thread CT;
Canvas canvas = new Canvas();
Dimension size = new Dimension(WIDTH, HEIGHT);
Camera camera;
Controls controls;
PlayerTest pt;
BufferStrategy BS;
Graphics graphics;
//I'm declaring the arrayList here
public ArrayList<Rectangle> bounded = new ArrayList<Rectangle>();
public Launcher() {
Sprites.resources();
controls = new Controls();
GUI();
//The camera class is the one in which I'm trying to access the list
//It's there right now just to test, I plan on changing it later
camera = new Camera(this, controls, 0, 0);
pt = new PlayerTest(this, canvas.getWidth() / 2, canvas.getHeight() / 2);
Tiles.tileSets();
CT = new Thread(this);
START();
}
public void GUI() {
setTitle(title);
setPreferredSize(size);
setResizable(false);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
addKeyListener(controls);
canvas.setPreferredSize(size);
canvas.setMaximumSize(size);
canvas.setMinimumSize(size);
canvas.setFocusable(false);
add(canvas);
setVisible(true);
}
public void render() {
BS = canvas.getBufferStrategy();
if(BS == null) {
canvas.createBufferStrategy(3);
return;
}
graphics = BS.getDrawGraphics();
graphics.setColor(Color.ORANGE);
graphics.fillRect(0, 0, WIDTH, HEIGHT);
Rectangle cam = new Rectangle((int)camera.getX(),
(int)camera.getY(),
camera.getWidth(),
camera.getHeight());
//Here I'm looping to get my tiles
for(int x = 0; x < 64; x++) {
for(int y = 0; y < 64; y++) {
Tiles.getTile(LevelCode.code[y][x]).setBounds( x * 50 - (int)camera.getXof(), y * 50 - (int)camera.getYof());
//Here I'm adding the rectangles from each tile into the array
bounded.add(new Rectangle(Tiles.getTile(code[y][x]).getBounds()));
}
}
pt.render(graphics);
BS.show();
graphics.dispose();
//Here after I render the tiles I clear the list, for my updates, then //repopulate
bounded.clear();
}
public ArrayList<Rectangle> getList() {
return bounded;
}
}
答案 0 :(得分:-1)
同步(如果操作正确)意味着这不是线程安全问题,尽管您还没有发布实际代码,因此您可能做错了。
这里最可能的情况是,实际上有多个ArrayList
并且您访问了错误的toString
。尝试检查ID(当你forEach
时#之后的数字),并确保两个地方的ID相同。