Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (513)
Games in Android Showcase (120)
games submitted by our members
Games in WIP (577)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1] 2
  ignore  |  Print  
  [Solved] Using ArrayList<> adding and removing objects  (Read 1634 times)
0 Members and 1 Guest are viewing this topic.
Offline _Scyth_

Junior Duke





« Posted 2013-10-21 19:20:19 »

Ok, so I'm planning on using ArrayList<> to add a PlayerRocket every time a rocket is fired.

I know that I can add them by using the add(Object o) method of the ArrayList<>.

Now what my problem is, is that my PlayerRocket has a boolean which says whether the rocket is active or not, and when that equals false, i need to remove that specific rocket from the arraylist. When i read the documentation, it says that using the method remove(Object o) removes the first one of that object off the list, how can i remove specific ones.

OR

is there an alternative, maybe where i can create my own ArrayList<> type class because i will need to iterate through the list as well?

Any help much appreciated
Offline Zhon

Junior Duke


Medals: 4



« Reply #1 - Posted 2013-10-21 19:39:21 »

I don't understand the problem.
Why isn't iterating through the list working?
Btw if your list contains only Rockets you can use Generics so you don't need to do type casting.
Offline wookoouk

Senior Newbie





« Reply #2 - Posted 2013-10-21 19:45:36 »

is this what you want?:


1  
2  
3  
4  
5  
6  
7  
ArrayList<PlayerRocket> playerRocketsArray = new ArrayList<>(PlayerRocket);

for(PlayerRocket pr: playerRocketsArray){
   if(wantToRemoveRocket){
      playerRocketsArray.remove(pr);
   }
}


although this can cause issues (bad to remove items from a list you are looping through)

so this may be better for you:

1  
2  
3  
4  
5  
ArrayList<PlayerRocket> playerRocketsArray = new ArrayList<>(PlayerRocket);
for (Iterator i = playerRocketsArray.listIterator(); i.hasNext();) {
   PlayerRocket pr = (PlayerRocket) i.next();
   if (wantToRemoveRocket) i.remove();
}
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline _Scyth_

Junior Duke





« Reply #3 - Posted 2013-10-21 20:26:39 »

Thanks for the help so far, I think I can get to answer from here, what I'm looking for is once the active boolean equals false, then the rocket needs to be removed from the list, but I'm sure I can simply do an if check in the loop, my only problem is, i'll need it to iterate through this every time i call the repaint method will this slow down my game?
Because the rocket shouldnt be rendered if it isnt active, that way i want to remove it from the screen and list.
Offline _Scyth_

Junior Duke





« Reply #4 - Posted 2013-10-21 20:30:32 »

Turns out I can't use ArrayList<>. it isnt included in the libraries that get delivered to the device im working for.

How can I go about creating a clone of this class?
Offline wookoouk

Senior Newbie





« Reply #5 - Posted 2013-10-21 20:31:16 »

It sounds like pretty standard bullet removal. My standard approact is as follows (not in code, just example)

on each render(re paint)

loop through bullets (as in previous post)
check if the bullet can be remove (I useally give bullets a 'life time' and when they hit zero (and have not hit anything) remove them).
if it needs removing, remove it (as shown in previous post).
repeat.

Unless there are thousands of bullets (rockets in this case) or they need a lot of logic ran against them or the game is running on an old/slow device, just do this in the render loop.

if it does effect your FPS, just create a thread for this.

If this is of use and you would like me to put it into code just say.
Offline wookoouk

Senior Newbie





« Reply #6 - Posted 2013-10-21 20:32:11 »

.....ArrayList<> is bog standard java...
Offline _Scyth_

Junior Duke





« Reply #7 - Posted 2013-10-21 20:35:35 »

It was a lot of use! Thank you, gives me the theory to it.

Err... Yeah blame RIM. I'm working with the BlackBerry JDE 4.5.0 and when i try and import it, it wont let me, which means I can't use it Sad
So now i need to try and create a clone of it, which I'm skeptical of, because I'm not sure what the <> part of the ArrayList means.
Offline wookoouk

Senior Newbie





« Reply #8 - Posted 2013-10-21 20:39:49 »

Very odd. I have not worked with the blackberry JDT so cannot really comment.

<> is the object type. You can ignore this and get away with some clever tricks (as mentioned by a previous user)

but it just means that if your Array (or ArrayList) if going to hold a bunch of strings, you are telling it in advance. Just tell it the class. in this case, your array holds many PlayerRocket(s) so 'new ArrayList<PlayerRocket>'

out of interest, can you do the following without it complaining:

1  
java.util.ArrayList<String> test = new java.util.ArrayList<String>();

Offline Phibedy

Senior Duke


Medals: 9



« Reply #9 - Posted 2013-10-21 20:40:33 »

I wouldn't use an arraylist in this case. Maybe you could have a look at LinkedList, it's much faster in removing elements.
In addition you can't remove an element out of the list while you are iterating that way.

pseudocode:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
LinkedList<PlayerRocket> playerRockets;
ArrayList<PlayerRocket> toremove;

public void checkPlayerRockets(){

//add rockets to the remove list
for(PlayerRocket pr:playerRockets){
if(pr.shouldBeRemoved(){
toremove.add(pr)
}
}
//remove rockets
for(PlayerRocket pr:toremove){
playerRockets.remove(pr)
}
toremove.clear();

}
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline _Scyth_

Junior Duke





« Reply #10 - Posted 2013-10-21 20:51:01 »

out of interest, can you do the following without it complaining:

1  
java.util.ArrayList<String> test = new java.util.ArrayList<String>();



Nope it complains. I'll try and create my own class.

@Phibedy, why can't I just remove from the array list?
Offline wookoouk

Senior Newbie





« Reply #11 - Posted 2013-10-21 21:01:28 »

as i said erlier, removing from a list you are looping through will break it.

e.g.

at item 5 of 10.

item 5 gets removed. there are no longer 10 items, loop get confused and breaks.
That is why you should use the 'hasNext()' loop i mentioned before or LinkedList way.

I had a look, blackberry does not have arraylists like you said it has its own version(s), you can write your own arraylist but I think blackberry wants you to use something like their 'Vector' class. see here: http://stackoverflow.com/questions/1428891/blackberry-jde-arraylist/1429744#1429744
Offline _Scyth_

Junior Duke





« Reply #12 - Posted 2013-10-21 21:12:49 »

Looks like I have two options now.
I can either make my own one, or try and use this one : http://www.blackberry.com/developers/docs/4.3.0api/net/rim/device/api/collection/util/UnsortedReadableList.html

honestly, I think my best idea would be to create my own one. That way i have complete control over it.
Offline _Scyth_

Junior Duke





« Reply #13 - Posted 2013-10-21 21:15:09 »

I found a much better way :O
Blackberry has an Arrays class, if i extend that or even just use it on its own then I'm sorted
Offline Longarmx
« Reply #14 - Posted 2013-10-21 23:27:02 »

When you try to add or remove objects in an enhanced for loop, it throws a ConcurrentModificationException.

Offline Cero
« Reply #15 - Posted 2013-10-22 02:59:31 »

iterate backwards starting from highest index, then i--
a for loop not for each which uses an iterator
now you can, on the fly remove elements without a problem

Offline relminator
« Reply #16 - Posted 2013-10-22 03:07:22 »

Why "remove" when you can "reuse"?  Much easier and faster too.
Offline Phibedy

Senior Duke


Medals: 9



« Reply #17 - Posted 2013-10-22 17:04:47 »

out of interest, can you do the following without it complaining:

1  
java.util.ArrayList<String> test = new java.util.ArrayList<String>();



Nope it complains. I'll try and create my own class.

@Phibedy, why can't I just remove from the array list?

Because you can't remove an object out of the list while you are iterating: http://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html

You could also do it that way: http://stackoverflow.com/questions/13307471/concurrent-modification-exception-in-java
but I would prefere mine.
Offline Jeremy
« Reply #18 - Posted 2013-10-22 19:17:05 »

I wrote a really hacky solution for this, the reason is because when you get more complex iterations you cannot use an iterator and predict which elements to remove via it.

Like for example, the UI  subsystem receives a mouse-press, the UI subsystem iterates through it's list of buttons and execute the appropriate button's handler. In the button's handler you remove the button from the UI subsytem, thus throwing a concurrent modification exception.

You can create a shallow clone your set as you iterate (not very memory efficient), or you can use CopyOnWriteArrayList . I wrote a solution for this (I am not very familiar with the JDK so it may be a redundant implementation) but you can see it here. It essentially stores all mutations to the list and only applies them when data is required to be retrieved about the arraylist. I.e, inserting an element or removing an element doesn't do anything immediately to the list. Creating an iterator into the list applies the mutations, getting an element from the list applies the mutations, getting the size of the list applies the mutations etc.

https://github.com/JeremyWildsmith/JevaEngineSrc/blob/master/JevaCore/src/jeva/util/StaticSet.java

JevaEngine, Latest Playthrough (This demo is networked with a centralized server model)

http://www.youtube.com/watch?v=rWA8bajpVXg
Offline _Scyth_

Junior Duke





« Reply #19 - Posted 2013-10-22 19:23:33 »

I've created my own ArrayList class. With the JDK I'm now allowed to use type so it's specific for my PlayerRocket:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
package {...}data;

import {...}PlayerRocket;

public class ArrayList {
   
   // Constants
   private final int DEFAULT_CAPACITY = 16;
   
   // Store the objects into an array
   public PlayerRocket[] elements;
   
   // Integer
   private int size = 0;
   
   // Methods
   // Constructor
   public ArrayList()
   {
      // set the default capacity of the array
      elements = new PlayerRocket[DEFAULT_CAPACITY];
     
   }
   // Add the object to the array
   public void add(PlayerRocket e)
   {
      if(getSize() >= DEFAULT_CAPACITY)
      {
         // Do nothing can't have more than 16 on screen at once
      }
      else
      {
         // add the object at specific point
         elements[size++] = e;
      }
   }
   
   
   // Remove the object at a certain location
    public void remove(int i) {
       // Check to see if it will cause an error
           if (i < 0 || i > elements.length) {
               throw new ArrayIndexOutOfBoundsException();
           } else {
              // now set it to null
               elements[i] = null;
               // create a temporary list of objects
               PlayerRocket[] tmp = new PlayerRocket[--size];
               int foo = 0;
               // iterate through the elements list and add any non-null to tmp
               for(int j = 0; j < elements.length; j++) {
                   if(elements[j] != null) {
                       tmp[foo] = elements[j];
                       foo++;
                   }
               }
               // make elements equal to the tmp
               elements = tmp;
           }
       }

   
   // Getters and Setters
   public int getSize() {
      return size;
   }
   public void setSize(int size) {
      this.size = size;
   }
   
   public PlayerRocket[] getContents()
   {
      return elements;
   }
   
   public PlayerRocket getElement(int i)
   {
      return elements[i];
   }

}


And if i removed whilst iterating, i get an ArrayOutOdBoundsException.

Also I cannot use the LinkedList. It isnt available to me
Offline Jeremy
« Reply #20 - Posted 2013-10-22 19:29:50 »

I've created my own ArrayList class. With the JDK I'm now allowed to use type so it's specific for my PlayerRocket:
1  
2  
3  
package {...}data;

import {...}PlayerRocket;


And if i removed whilst iterating, i get an ArrayOutOdBoundsException.

Also I cannot use the LinkedList. It isnt available to me

Have you looked at my solution? It isn't perfect, but I think it'll work fine or at least inspire some ideas for you:
https://github.com/JeremyWildsmith/JevaEngineSrc/blob/master/JevaCore/src/jeva/util/StaticSet.java

I get where you're going with your solution but I don't think it's a very good general solution.

JevaEngine, Latest Playthrough (This demo is networked with a centralized server model)

http://www.youtube.com/watch?v=rWA8bajpVXg
Offline _Scyth_

Junior Duke





« Reply #21 - Posted 2013-10-22 19:44:09 »

Jeremy in your StaticSet.java you use ArrayList and Iterator. Neither of these are available to me whereas the NoSuchElement is.
Could I possibly use my own ArrayList as a substitute for the ArrayList<>. However the iterator part i@m not too sure on.
Offline Jeremy
« Reply #22 - Posted 2013-10-22 19:52:13 »

Jeremy in your StaticSet.java you use ArrayList and Iterator. Neither of these are available to me whereas the NoSuchElement is.
Could I possibly use my own ArrayList as a substitute for the ArrayList<>. However the iterator part i@m not too sure on.

Replace ArrayList with UnsortedReadableList (of course, now they won't be sorted.)

How are for-each loops implemented without iterators D: ? Man that is really awkward... Maybe try Enumeration: http://www.blackberry.com/developers/docs/5.0.0api/java/util/Enumeration.html

JevaEngine, Latest Playthrough (This demo is networked with a centralized server model)

http://www.youtube.com/watch?v=rWA8bajpVXg
Offline _Scyth_

Junior Duke





« Reply #23 - Posted 2013-10-22 19:55:07 »

Yeah, they've left out some classes that make things easier. I'll use the unsortedreadablelist. Does sorting matter? and I'll also check the enumeration for the for each, can i not simply use a basic for loop for this?
Offline Jeremy
« Reply #24 - Posted 2013-10-22 19:59:54 »

Yeah, they've left out some classes that make things easier. I'll use the unsortedreadablelist. Does sorting matter? and I'll also check the enumeration for the for each, can i not simply use a basic for loop for this?

Scratch my solution. You need a sorted list to store the mutations (they need to be applied in the proper order.)

Sorry for wasting your time.

That BB JDE seems terribad. Last I checked, BlackBerry (canadian company) was doing terribly and is thinking of selling to an Chinese organization.

The simplest solution for this (psuedo code)

ArrayList garbage;

for(item i : myList)
{
    if(someCondition)
        garbage.add(i);
}

myList.removeAll(garbage);


But it isn't very memory efficient. You could reuse your garbage arraylist which would help a lot. Ofcourse, you might run into the problem I've stated above (in my first post in this thread)

JevaEngine, Latest Playthrough (This demo is networked with a centralized server model)

http://www.youtube.com/watch?v=rWA8bajpVXg
Offline _Scyth_

Junior Duke





« Reply #25 - Posted 2013-10-22 20:03:39 »

Yeah but its the library im most comfortable with, also gives me a market.

Here would this "list" help me at all?
http://www.blackberry.com/developers/docs/4.5.0api/net/rim/device/api/collection/List.html

 I think it might, if i can create a way to clone it then i could possibly clone the arraylist to another arraylist, remove the object from the temporary arraylist and then at the end set the permanent one the same as the tmp one?
Offline Jeremy
« Reply #26 - Posted 2013-10-22 20:05:49 »

Yeah but its the library im most comfortable with, also gives me a market.

Here would this "list" help me at all?
http://www.blackberry.com/developers/docs/4.5.0api/net/rim/device/api/collection/List.html

 I think it might, if i can create a way to clone it then i could possibly clone the arraylist to another arraylist, remove the object from the temporary arraylist and then at the end set the permanent one the same as the tmp one?

Yeah, cloning should work fine. Just make sure you only do a shallow clone. The only problem with this approach (and if it isn't a problem for you - and it probably isn't) is that you end up creating a lot of shallow clones. Just be clever about when you clone and it shouldn't be a problem.

JevaEngine, Latest Playthrough (This demo is networked with a centralized server model)

http://www.youtube.com/watch?v=rWA8bajpVXg
Offline _Scyth_

Junior Duke





« Reply #27 - Posted 2013-10-22 20:15:23 »

Yeah, for the cloning I'm thinking of two solutions to it.
To clone it everytime i remove an element, or to create another array with each of the positions of the objects to be removed, then clone the arraylist, iterate through the array with the positions, then remove the objects from the temporary one, and then set the original list the same as the temp one.

Now i just need to try and find away to clone it :/
Offline _Scyth_

Junior Duke





« Reply #28 - Posted 2013-10-22 20:37:44 »

Everything seems to be working okay-ish.

Multiple rockets will fire, but if i move the ship, therefore moving the starting x position of the rocket im getting the array out of bounds exception. Here is my porjectile, player rocket, array list, and methods that i use that when firing a rocket.

ArrayList
http://pastebin.java-gaming.org/b4d17773178

Projectile
http://pastebin.java-gaming.org/4d17781387c

PlayerRocket ( extends projectile )
http://pastebin.java-gaming.org/d1771983c73

The Methods
http://pastebin.java-gaming.org/177180c4371

My error is
1  
         elements[size++] = e;


in the
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
   // Add the object to the array
   public void add(PlayerRocket e)
   {
      if(getSize() >= DEFAULT_CAPACITY)
      {
         // Do nothing can't have more than 16 on screen at once
      }
      else
      {
         // add the object at specific point
         elements[size++] = e;
      }
   }

of the projectile.

and it is telling me
1  
size = 2


Offline DQQAYME
« Reply #29 - Posted 2013-10-22 21:05:40 »

Hm, i need re read question Wink
this help?
1  
2  
3  
4  
5  
6  
7  
8  
9  
   for(int i = 0; i < Bullets.size(); i++){
      Bullet bu = Bullets.get(i);  
      bu.blalbalball();
     
      if(bu.isDead()){
         Bullets.remove(i);
         i--;
      }
   }

Pages: [1] 2
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Longarmx (52 views)
2014-10-17 03:59:02

Norakomi (43 views)
2014-10-16 15:22:06

Norakomi (33 views)
2014-10-16 15:20:20

lcass (37 views)
2014-10-15 16:18:58

TehJavaDev (68 views)
2014-10-14 00:39:48

TehJavaDev (68 views)
2014-10-14 00:35:47

TehJavaDev (60 views)
2014-10-14 00:32:37

BurntPizza (73 views)
2014-10-11 23:24:42

BurntPizza (45 views)
2014-10-11 23:10:45

BurntPizza (86 views)
2014-10-11 22:30:10
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!