Omar
Omar

Reputation: 1091

Understanding ArrayList in conjunction with Objects

I am experimenting with creating my own particle effect (simple) when the mouse is clicked on the screen. I dont think the language is relevant (but I'm still learning)

Is my logic as follows correct:

Each time I click, the particles get added to an ArrayList to be iterated through to increment size, color and opacity

Now this would still work if I had multiple clicks on the screen because each set of particles would simple be added to the ArrayList...

however, this does not seem efficient because when the first particle blast has ended, it is no longer needed in the ArrayList and should not take up memory

Could someone help me with the logic? And would animating a PNG series be more efficient than dynamically creating your own particle effect?

Thanks

PS - I'm not creating a game/application...just experimenting with concepts I'm learning

Upvotes: 1

Views: 114

Answers (2)

etherous
etherous

Reputation: 709

How about making the particles expire?

class Particle
{
    static final long EXPIRE_TIME = 2000; // 2 seconds

    final long expireTime;

    public Particle ()
    {
        expireTime = System.currentTimeMillis() + EXPIRE_TIME;
    }
}

SortedSet<Particle> particles = new TreeSet<>(new Comparator<Particle>{
    public compare (Particle a, Particle b)
    {
        if(a.expireTime < b.expireTime)
            return -1;
        if(a.expireTime > b.expireTime)
            return 1;
        return a.hashCode() - b.hashCode();
    }
});

Then you can add the particles to the 'particles' set using the add method. On an interval, like each time the view is updated, remove all particles from the front of the set which have expired (their expireTime field is less than System.currentTimeMillis)

Upvotes: 1

Straw1239
Straw1239

Reputation: 689

You should delete expired particle effects. It would probably be more suitable to use a LinkedList for this, as you can iterate over it and remove any expired elements in constant time. ArrayList and LinkedList both implement the List interface, so if you use a List in your code it can accept either. Be careful to avoid indexed access on linked lists as it is slow; whenever possible use an iterator or for-each loop.

Iterator<ParticleBlast> itr = particles.iterator();
while(itr.hasNext())
{
    ParticleBlast next = itr.next();
    if(next.hasExpired()) itr.remove();
}

Upvotes: 1

Related Questions