We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Removing element from array of objects
Page Index Toggle Pages: 1
Removing element from array of objects (Read 1275 times)
Removing element from array of objects
Oct 28th, 2008, 3:56am
 
Well, I think it´s simple, but I´m having a lot of trouble when trying to delete an object element inside an array of objects. this function is what I have so far, it doesn´t crash though it doesn´t work.


void killShot(int n){
 shot[] ns = new shot[0];
 for (int i = 0; i < shots.length; i++){
   if (n != shots[i].num){
     ns = (shot[]) append(ns, shots[i]);
   }
 }
 shots = (shot[]) subset(shots, 0);
 println(shots.length);
 for (int i = 0; i < ns.length; i++){
   shots = (shot[]) append(shots, ns[i]);
 }
}
Re: Removing element from array of objects
Reply #1 - Oct 28th, 2008, 12:29pm
 
I think something like:
shots=(shot[])concat(shots.subset(0,n),shots.subset(n+1,shots.length));

should work.
Re: Removing element from array of objects
Reply #2 - Oct 28th, 2008, 9:59pm
 
Might be easier and more efficient with a good old ArrayList. Processing's array functions are useful when starting to code, but Collections are more flexible... Smiley
Re: Removing element from array of objects
Reply #3 - Oct 30th, 2008, 5:07pm
 
Quote:
I think something like:
shots=(shot[])concat(shots.subset(0,n),shots.subset(n+1,shots.length));

should work.


Cannot invoke subset(int, int) on the array type shot[]

What is this array list?
Re: Removing element from array of objects
Reply #4 - Oct 31st, 2008, 12:08am
 
ArrayLists are standard java collections that are dynamic (ie allow you to add and remove elements from them). much more useful than plain old arrays

http://www.java-tips.org/java-se-tips/java.lang/use-of-arraylist-class.html

you can insert data anywhere but there's a hit for doing it at the start of the list as it must shuffle all the other elements down one. ditto deleting from the start.

your killShot(n) would just be shots.remove(n) where shots is the arraylist.
Page Index Toggle Pages: 1