User talk:Awesomeness
- Archived talks:
- Archived Talk 20090502
Okay, I need to make a list of bullets. I have made a bullet class and everything, but I need a special list that will let me access all of the bullets in a while/for loop and be able to add and remove them at any time and never mess up. If I did this in a normal array I could do a for loop and access using an increasing number, but I wouldn't know when to stop. In a while loop, if I used while(bulletsArray[x] != null) and then increment x, after I remove my first bullet that say, hit a wall, it will stop there. I need help!
- Thanks,
- Awesomeness 14:02, 2 May 2009 (UTC)
I think this will do:
ArrayList<Bullet> bullets = new ArrayList<Bullet>(); for (int i = 0; i < bullets.size(); i++) { Bullet bullet = bullets.get(i); if (bullet.needRemove()) { // I think this will work // bullets.remove(i--); // but usually I do bullets.remove(bullet); i--; } }
Here I assume that you use ArrayList to store you bullets and your bullet's classname is Bullet. If you use a plain array to keep the bullets, consider change to ArrayList. It is more flexible. » Nat | Talk » 14:09, 2 May 2009 (UTC)
- Oh my gosh! You're right! ArrayList is way more flexible! I looked at the documentation; you don't even have to increment or decrement anything! The function remove() shifts the other elements to the left already! Thanks! Awesomeness 14:14, 2 May 2009 (UTC)
- Be sure don't use for-each style (
for(Bullet bullet : bullets)
or you will get ConcurentModificationException when you remove element (this is per java spec, but I still use the for-each style and didn't get this exception actually). And when you scroll through the array like one I mentioned, be sure you do i--, or you will just skip one element. » Nat | Talk » 14:19, 2 May 2009 (UTC)
- Be sure don't use for-each style (
- Oh, you're right. Awesomeness 14:27, 2 May 2009 (UTC)