aspose file tools*
The moose likes Beginning Java and the fly likes Object Creation Within Loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Object Creation Within Loop" Watch "Object Creation Within Loop" New topic
Author

Object Creation Within Loop

Will Blanc
Greenhorn

Joined: Jul 11, 2008
Posts: 8
class Player:
main method:

//HOW DO YOU DO the following using ArrayList<Player>?
for(int i = 0; i < players.length; i++)
players[i] = new Player();
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3855

What are you trying to achieve here? I guess players is a reference to array of Player? So,in your code you are populating the array with new Player objects( assuming your players array is initialised).


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Bert Deville
Greenhorn

Joined: Oct 10, 2008
Posts: 8
I assume you want to do something like this, but want to replace the array with an Arraylist :



An Arraylist, unlike an array, doesn't have a fixed size. It just grows and shrinks when you add or remove elements. So instead of creating an array with size 10 and loop through it to add Player objects, you can simply create an ArrayList without an initial size, then loop 10 times to add a Player object. Something like this :

[edit]Deleted solution. CR[/edit]
[ October 10, 2008: Message edited by: Campbell Ritchie ]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39882
    
  28
I am very sorry to do this, Bert, but we don't like giving out answers like that straight off. Look at the heading above the contents page for the beginners' forum: "We are here to learn." You have provided lots of useful hints, but Will will learn a lot more by working out how to fill in the last bit. So I have felt obliged to delete the bit of the solution you posted.

Please don't be annoyed with me.

I shall give Will this hint: parts of what I deleted are similar to what you are using for populating the array.

CR
Bert Deville
Greenhorn

Joined: Oct 10, 2008
Posts: 8
I'm sorry, I thought it would be good for his learning to see both array and ArrayList side by side and spot the differences. But I understand your reasoning, no hard feelings.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39882
    
  28
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Object Creation Within Loop