英文:
Adding new object by pressing left mouse
问题
有一个包含Object
实例(Sprites
)的数组,有一个通过按下鼠标左键来向数组中添加新对象的方法:
private void addSprite() {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
Sprite sprite = new Ball(x, y);
if (sprites[sprites.length - 1] == null){
sprites[sprites.length - 1] = sprite;
}else if (sprites[sprites.length - 1] != null){
Sprite[] temp = new Sprite[sprites.length * 2];
System.arraycopy(sprites, 0, temp, 0, sprites.length);
sprites = temp;
}
}
});
}
如果arr
已满,我会创建一个新的临时数组,大小为sprites.length * 2
,并将所有元素复制到一个临时数组
中,然后更改链接sprites = temp
,但是我遇到了NullPointerException
。任务是仅使用数组而不是ArrayList
来添加新对象。
我做错了什么?
英文:
Got an array of Object
instances (Sprites
), got method to add a new object to array by pressing left mouse button:
private void addSprite() {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
Sprite sprite = new Ball(x, y);
if (sprites[sprites.length - 1] == null){
sprites[sprites.length - 1] = sprite;
}else if (sprites[sprites.length - 1] != null){
Sprite[] temp = new Sprite[sprites.length * 2];
System.arraycopy(sprites, 0, temp, 0, sprites.length);
sprites = temp;
}
}
});
}
If arr
is full I create new temporary array, size of sprites.length * 2
, and copy all elements in a temporary array
, and change link sprites = temp
, and I've got NullPointerException
. Task is adding new objects using only arrays, not ArrayList
.
What am I doing wrong?
答案1
得分: -1
像这样工作:
private void addSprite() {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
Sprite sprite = new Ball(x, y);
if (sprites[count] == null){
sprites[count] = sprite;
count++;
}else if (sprites[count] != null){
Sprite[] temp = new Sprite[sprites.length + 1];
System.arraycopy(sprites, 0, temp, 0, sprites.length);
temp[sprites.length] = sprite;
sprites = temp;
}
}
});
}
如果创建数组大小:`sprites.length * 2`:
问题是 Java 会尝试对数组的 `null` 元素进行 `update` 和 `render`。
如果创建 `sprites.length + 1` 并在最后一个 `index` 处添加元素,数组中就不会有 `null` 元素,它将正常工作。
英文:
work like this:
private void addSprite() {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
Sprite sprite = new Ball(x, y);
if (sprites[count] == null){
sprites[count] = sprite;
count++;
}else if (sprites[count] != null){
Sprite[] temp = new Sprite[sprites.length + 1];
System.arraycopy(sprites, 0, temp, 0, sprites.length);
temp[sprites.length] = sprite;
sprites = temp;
}
}
});
}
If create array size: sprites.length * 2
:
problem is java try to update
and render
null
elements of array
If create sprites.length + 1
and add on an last index
element there is no null
elements in array, it's work fine.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论