Generics, where it all began..

Hello,

I started my coding hobby year ago wit jdk 6. Generics have been supported since jdk 5 so I never had bad problems using and adding multiple objects, for example, in shooting games because I was able to use ArrayLists and LinkedLists when I wanted to add multiple shots (like shooting with machine gun).

(My question comes after this example:)

For example I painted all the machine gun bullet objects just with this simple code:

for (Bullet b : bullet){
b.paint(g);
}

and in Thread there was something like this:

for( Bullet b : bullet){
b.move();
}

and I added new bullets in Keypressed like this:

bullet.add(new Bullet(some,parameters);

Now my question is that how things were done before the generics? I am doing one mobile shooting game and I cannot use generics in that. Creating many bullet objects without collections would be very time consuming.

I hope some on can help me with this.

You can still use collections, you just have to manually cast things that you get out of them, like so:


List bullets = new LinkedList();

// bang!
bullets.add( new Bullet() );

for( Object o : bullets )
{
   ( ( Bullet ) o ).move();
}

The downside, apart from the extra tedious typing, is that the nice compile-time error you get when you try to add a non-bullet object to the bullet list becomes an execution-time ClassCastException when you retrieve and cast the erroneous object.

Thanks!

Generics simply add the proper class-casts when compiling.

Oops, it didn’t work.

I should have put more emphasize on that I’m doing midp application. I’m doing cldc 1.0 and midp 1.0 application, so I don’t have linkedLists and I cannot use these for-each loops which became same time with generics, I think.

Only collections that I can use are Vector, Stack, Hashtable and Enumeration.

So how can I do it with these resources?

You can use a Vector like you would a LinkedList, and an Enumeration like you would an Iterator, like so:


Vector bullets = new Vector();

// bang!
bullets.add( new Bullet() );

Enumeration b = bullets.elements();
while( b.hasMoreElements() )
{
   ( ( Bullet ) b.nextElement() ).move();
}

but, to pre-empt Riven’s forthcoming reply, a Vector has O(1) access to it’s elements (Unlike a LinkedList), so it’s better to bypass the Enumeration bit and access directly:


for( int i = 0; i < bullets.size(); i++ )
{
   ( ( Bullet ) bullets.get( i ) ).move();
}

…especially in JME environments where the garbage collector probably isn’t as clever as you’d like.

Thanks, I’ll try it.

Thank you very much! Even if I’m drunk now, I got it work!

Are you sure that for- thing works like this:


for( int i = 0; i < bullets.size(); i++ )
{
   ( ( Bullet ) bullets.get( i ) ).move();
}

Because there doesn’t seem to be “get” - method…

Program is working as well as I hoped so Thank’s again!

You’re right there, I was looking at the j2se Vector javadocs. In CDLC, it’s .elementAt( int index )