This site requires JavaScript, please enable it in your browser!
Greenfoot back
sse0005
sse0005 wrote ...

2015/9/22

creating multiple objects in a loop

sse0005 sse0005

2015/9/22

#
I can't figure out why this won't work. it will compile but no lobster will show up.
List<Lobster> lobster = new ArrayList<Lobster>(numLobster);
        
        for (Lobster larry : lobster)
        {

            addObject(larry,Greenfoot.getRandomNumber(560),Greenfoot.getRandomNumber(560));
            
        }
i would appreciate any advice.
Super_Hippo Super_Hippo

2015/9/22

#
You create a new List with 'numLobster' elements. These elements are 'null'. Then you have a for-each that tries to add all elements to the world. But the elements are only 'null', so nothing is added. You can either add the following line in line 5
larry = new Lobster();
or if you don't need the list, you can replace all with this line:
for (int i=0; i<numLobster; i++) addObject(larry,Greenfoot.getRandomNumber(560),Greenfoot.getRandomNumber(560));
davmac davmac

2015/9/22

#
Super_Hippo wrote...
You create a new List with 'numLobster' elements. These elements are 'null'.
No; an empty list is created (with an initial capacity of 5). The for-each loop then does nothing because the list is empty. sse0005, you need a regular counting loop instead of a for-each loop; you need to create a new Lobster and it to the world in each iteration of the loop. If you need the 'lobster' list later on, then you should also add the created lobster to this list.
Super_Hippo Super_Hippo

2015/9/22

#
Ok, it is empty, not null. But why is the initial capacity 5? Shouldn't it be the capacity 'numLobsters' (providing that numLobsters is an int)? If there wouldn't be that int, it should be 10, not 5.
Java API wrote...
ArrayList() Constructs an empty list with an initial capacity of ten.
Source: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#constructor_summary
davmac davmac

2015/9/22

#
Ok, it is empty, not null. But why is the initial capacity 5? Shouldn't it be the capacity 'numLobsters' (providing that numLobsters is an int)?
You are absolutely right. I'm not sure where I got that 5 from, sorry.
You need to login to post a reply.