(libgdx/java) ArrayList няма да изчисти/изтрие екземпляр на клас?

Клас артикул:

       public class Item {
          public float x, y, speedx, speedy;
        public Rectangle container;
        public Texture texture;
       static Timer timer = new Timer();
      static  int amount;
       static int spawned;
        public int itemtype;
        //   float delay = 1; // seconds

        public void move() {
            x += speedx;
            y += speedy;

            container.x = x;
            container.y = y;

        }
  public void setTexture(int itemtype){
        switch(itemtype){
            case 1:
                texture = new Texture("items/item1.png");
                break;
            case 2:
                texture = new Texture("items/item2.png");
                break;
            case 3:
                texture = new Texture("items/item3.png");
                break;
            case 4:
                texture = new Texture("items/item4.png");
                break;
            case 5:
                texture = new Texture("items/item5.png");
                break;
            case 6:
                texture = new Texture("items/item6.png");
                break;
            case 7:
                texture = new Texture("items/item7.png");
                break;
            case 8:
                texture = new Texture("items/item8.png");
                break;
            case 9:
                texture = new Texture("items/item9.png");
                break;
            case 10:
                texture = new Texture("items/item10.png");
                break;
            default:
                texture = new Texture("items/error.png");
                break;
        }

    }
          public static void spawnItem(int amount){
            Item.amount = amount;
              mainscreen.items.clear();
                  //  for(int spawned = 0; spawned <= amount; spawned++){



                        timer.schedule(new Timer.Task() {

                            @Override
                            public void run() {
                                if (mainscreen.canclick == false) {
                                    Item item = new Item();
                                    item.x = 600;
                                    item.y = -42;
                                    item.speedx = -20;
                                    item.speedy = 0;
                                    Rectangle itemcontainer = new Rectangle();
                                    itemcontainer.x = item.x;
                                    itemcontainer.y = item.y;
                                    itemcontainer.width =                       mainscreen.container.getWidth() / 4f;
                                    itemcontainer.height = mainscreen.container.getHeight() - 15f;
                                    item.container = itemcontainer;
         item.itemtype = MathUtils.random(1, 10);
item.setTexture(item.itemtype);
                                    mainscreen.items.add(item);
                                    spawned++;
                                }
                                for (Item item : mainscreen.items) {
                                    if (item.x <= -4000) {
                                        if (spawned >= Item.amount) {
                                            mainscreen.canclick = true;


                                            timer.stop();
                                            spawned = 0;
                                        }

                                    } else {

                                    }
                                }
                           }
                        }, 0, 0.325f);

                }
    public void dispose(){
        texture.dispose();
    }
            }

Клас на основния екран:

public class mainscreen implements Screen, GestureDetector.GestureListener,InputProcessor {
    @Override
    public void render(float delta) {
        this.delta = delta;
        Gdx.gl.glClearColor(115 / 255F, 115 / 255F, 115 / 255F, 1 / 255F);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.setProjectionMatrix(camera.combined);

      if(Gdx.input.justTouched()) {

          Vector3 touch1 = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
          camera.unproject(touch1);


          if (debug.contains(touch1.x, touch1.y)) {
              items.clear();
          }

          if (start.contains(touch1.x, touch1.y)) {
          if (canclick == true) {

                  canclick = false;

    Item.spawnItem(20);
              }

          }
      }

}

РЕГИСТРАТОР: При първо щракване Старт: (След като таймерът приключи)

canclick: true
items list: [com.abc.luckyllama.Item@37237aa0, com.abc.luckyllama.Item@2de938e3, com.abc.luckyllama.Item@3cb912d5, com.abc.luckyllama.Item@2bae592c, com.abc.luckyllama.Item@774c083, com.abc.luckyllama.Item@633edeae, com.abc.luckyllama.Item@176557a6, com.abc.luckyllama.Item@4edb1b5f, com.abc.luckyllama.Item@6f8abadf, com.abc.luckyllama.Item@7a54d22e, com.abc.luckyllama.Item@473162a5, com.abc.luckyllama.Item@51a698ff, com.abc.luckyllama.Item@6bc08c56, com.abc.luckyllama.Item@37d9e6a2, com.abc.luckyllama.Item@7bb19eb6, com.abc.luckyllama.Item@1eb5805f, com.abc.luckyllama.Item@71780de3, com.abc.luckyllama.Item@9ec0998, com.abc.luckyllama.Item@7edf723d, com.abc.luckyllama.Item@4c5aa2c1]

След като щракнете върху бутона за отстраняване на грешки (изчиства arraylist):

canclick: true
items list: []

След като щракнете отново върху бутона за стартиране: (След като таймерът приключи)

 canclick: true
items list: [com.abc.luckyllama.Item@7d7cb9bc, com.abc.luckyllama.Item@1435cf42, com.abc.luckyllama.Item@117e1963, com.abc.luckyllama.Item@82bfd27, com.abc.luckyllama.Item@108214c7, com.abc.luckyllama.Item@2a77864a, com.abc.luckyllama.Item@4b232766, com.abc.luckyllama.Item@1cb629e0, com.abc.luckyllama.Item@1c92229d, com.abc.luckyllama.Item@ac1b293, com.abc.luckyllama.Item@588bbcba, com.abc.luckyllama.Item@75df6762, com.abc.luckyllama.Item@78d4358e, com.abc.luckyllama.Item@7f86452d, com.abc.luckyllama.Item@7aed480b, com.abc.luckyllama.Item@7407d443, com.abc.luckyllama.Item@2da6e708, com.abc.luckyllama.Item@604470bc, com.abc.luckyllama.Item@70f9d1af, com.abc.luckyllama.Item@3a16a63f, com.abc.luckyllama.Item@201288d2, com.abc.luckyllama.Item@6310ddfc, com.abc.luckyllama.Item@5d5a1c98, com.abc.luckyllama.Item@52727e52, com.abc.luckyllama.Item@669228d6]

Виждате, че елементите в ArrayList не са изчистени. Увеличи се. Мисля, че това е така, защото екземплярите на Item, създадени в spawnItem(), все още са там. Как да поправя това?

Забелязах, че всеки път, когато щракна върху бутона, няма повече елементи. Елементите се създават по-бързо. Но как да спрем това?


person AlGrande    schedule 22.02.2016    source източник
comment
Мисля, че част от критичния ви код липсва по-горе. Никъде по-горе не добавяте нищо към списъка, без незабавно да го премахнете. Между другото, изтичате копия на същата текстура, като използвате new Texture(...) и не запазвате препратката за по-късно изхвърляне.   -  person Tenfour04    schedule 22.02.2016
comment
Съжалявам, че добавих това по погрешка (при премахването му проблемът все още е там)   -  person AlGrande    schedule 23.02.2016
comment
Във вашите списъци има различни обекти, така че не се добавят обекти. Не е невъзможно да не изчистите обекти, когато извикате метод clear. Вероятно вашето кликване работи многократно.   -  person Fuat Coşkun    schedule 23.02.2016
comment
Забелязах, че всеки път, когато щракна върху бутона, елементите се появяват по-бързо. (таймерът спира ли по-бързо?) Но как да спра това?   -  person AlGrande    schedule 23.02.2016


Отговори (1)


Оправих го! Проблемът беше, че трябваше да създам Timer.Task отделно и да използвам task.cancel(); за спиране на Timer.Task:

import com.badlogic.gdx.utils.Timer;
public class Item {
public static Timer.Task task;
   public static void spawnItem(int amount){
        Item.amount = amount;

        task = new Timer.Task() {
            @Override
            public void run() {

                if (mainscreen.canclick == false) {
                    item = new Item();

                    item.x = 600;
                    item.y = -42;
                    item.speedx = -20;
                    item.speedy = 0;
                    Rectangle itemcontainer = new Rectangle();
                    itemcontainer.x = item.x;
                    itemcontainer.y = item.y;
                    itemcontainer.width = mainscreen.container.getWidth() / 3f;
                    itemcontainer.height = mainscreen.container.getHeight() - 15f;
                    item.container = itemcontainer;
                    item.itemtype = MathUtils.random(1, 10);

                    item.setTexture(item.itemtype);


                    mainscreen.items.add(item);
                    mainscreen.itemsspawned += 1;


                    //   mainscreen.items.remove(item);


                    spawned++;
                }
                for (Item item : mainscreen.items) {
                    if (item.x <= -4000) {
                        if (spawned >= Item.amount) {
                            mainscreen.canclick = true;

                            timer.clear();
                            timer.stop();
                            task.cancel();
                            spawned = 0;

                        }

                    }
                }


            }
        };


        timer.schedule(task, 0, 0.4f);

    }
}
person AlGrande    schedule 23.02.2016