• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object Creation Within Loop

 
Will Blanc
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3913
9
Chrome Fedora Hibernate
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Bert Deville
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic