简体   繁体   English

为什么我的 ArrayList 项目在消失时不会自行删除?

[英]Why aren't my ArrayList items removing themselves when they disapear?

I am trying to get my Asteroids game in Java to have the ArrayList container be removed once it's off screen.我正在尝试让我的小行星游戏 Java 将 ArrayList 容器从屏幕上移除。 I figured out how to stop having it print when off screen, but can see in my console the array continues to grow.我想出了如何在屏幕外停止打印它,但可以在我的控制台中看到数组继续增长。 Not sure where to go from here.不知道从这里到 go 的哪里。

I think the way I can get them to be removed when off screen is by either using the remove or set feature with arrayLists.我认为我可以通过使用带有 arrayLists 的删除或设置功能来在屏幕外删除它们。 Visually everything is disappearing right, but in the console my ArrayList is still growing.视觉上一切都在消失,但在控制台中我的 ArrayList 仍在增长。 I thought about setting a limit of how long it can be, but not sure if there is a better way than that.我考虑过设置它可以持续多长时间的限制,但不确定是否有比这更好的方法。

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;

public class AsteroidGame extends Frame {

    private int FrameWidth = 500;
    private int FrameHeight = 400;

    static public void main(String[] args) {
        AsteroidGame world = new AsteroidGame();
        world.show();
        world.run();
    }

    public AsteroidGame() {
        setTitle("Asteroid Game0");
        setSize(FrameWidth, FrameHeight);
        addKeyListener(new keyDown());
        addWindowListener(new CloseQuit());
    }

    public void run() {
        while (true) {
            movePieces();
            repaint();
            try {
                Thread.sleep(100);

            } catch (Exception e) {
            }
        }
    }

    private ArrayList asteroids = new ArrayList();
    private ArrayList rockets = new ArrayList();
    private Station station = new Station(FrameWidth / 2, FrameHeight - 20);

    public void paint(Graphics g) {
        station.paint(g);
        Iterator astIt = asteroids.iterator();
        while (astIt.hasNext()) {
            Asteroid rock = (Asteroid) astIt.next();
            if (rock.y >= 400 || rock.x >= 500){
                rock = null;
            } else {
                rock.paint(g);
            }

        }
        Iterator rocIt = rockets.iterator();
        while (rocIt.hasNext()) {
            Rocket rock = (Rocket) rocIt.next();
            if (rock.y >= 400 || rock.x >= 500) {
                rock = null;
            } else {
                rock.paint(g);
            }
        }

    }

    public void movePieces() {
        if (Math.random() < 0.3) {
            Asteroid newRock = new Asteroid(FrameWidth * Math.random(), 20, 10 * Math.random() - 5, 3 + 3 * Math.random());
            if (newRock.y >= 500 || newRock.x >= 500){

                asteroids.remove(0);

            } else{
                asteroids.add(newRock);
            }
            System.out.println(asteroids.size());

        }

        Iterator astIt = asteroids.iterator();
        while (astIt.hasNext()) {
            Asteroid rock = (Asteroid) astIt.next();
            if (rock.y >= 400 || rock.x >= 500) {
                rock = null;
            } else {
                rock.move();
                station.checkHit(rock);
            }


        }
        Iterator rocIt = rockets.iterator();
        while (rocIt.hasNext()) {
            Rocket rock = (Rocket) rocIt.next();
            if (rock.y >= 400 || rock.x >= 500) {
                rock = null;
            } else {
                rock.move(asteroids);
            }

        }

    }

    private class gameMover extends Thread {

        public void run() {
            while (true) {
                movePieces();
                repaint();
                try {
                    sleep(100);

                } catch (Exception e) {
                }
            }
        }
    }

Change:改变:

rock = null;

to:到:

astIt.remove();

Assigning null to the variable that has been assigned the value of an element of a List does absolutely nothing to either the List or the element in it;null分配给已分配 List 元素值的变量对 List 或其中的元素绝对没有任何作用; it only affects the value that the variable holds .它只影响变量持有的值。


As an aside, nice variable name choice of rock - it is appropraite for both types of object - either an abbreviation of "rocket" or a reasonable synonym for an astroid.顺便说一句, rock的变量名称选择不错——它适用于两种类型的 object——“rocket”的缩写或 astroid 的合理同义词。

Change rock = null;rock = null; to asteroids.remove(rock);asteroids.remove(rock); or astIt.remove();astIt.remove(); and it should be fine, also no need to set the variable to null as the garbage collector will take care of it for you.应该没问题,也无需将变量设置为 null,因为垃圾收集器会为您处理。
EDIT编辑
Actually asteroids.remove(rock);实际上是asteroids.remove(rock); will throw an exception as said in the comments of this answer, so nevermind it and use the other.将如本答案的评论中所述抛出异常,所以不要管它并使用另一个。

Also I think when in movePieces() you create a new rock and you check if this new rock is outside the screen, I don't think removing the first asteroid in the ArrayList is correct as you will not add the new rock (which may be right if the rock can actually randomly spawn outside the screen) but you will also remove a maybe fine working asteroid from the ArrayList (and thus from the game and the screen).另外我认为当你在movePieces()中创建一个新岩石并检查这个新岩石是否在屏幕之外时,我认为移除 ArrayList 中的第一颗小行星是不正确的,因为你不会添加新岩石(这可能如果岩石实际上可以在屏幕外随机生成,那是对的)但是您还将从 ArrayList 中(并因此从游戏和屏幕中)移除一颗可能正常工作的小行星。

So, personally I would change that part of code to:因此,我个人会将那部分代码更改为:

if (Math.random() < 0.3) {
        Asteroid newRock = new Asteroid(FrameWidth * Math.random(), 20, 10 * Math.random() - 5, 3 + 3 * Math.random());
        if (!(newRock.y >= 500 || newRock.x >= 500)){

            asteroids.add(newRock);
        }
        System.out.println(asteroids.size());

    }

But tell me if this works for you.但是告诉我这是否适合你。

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

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