-1

I am trying to generate planets and i want to know the best way of creating objects in a for loop. I also want to be able to interact with the objects in a for loop as well. For example changing their x and y. And help would be appreciated.

2 Answers2

1

Example:

List<Planet> planets = new ArrayList<>();
for(int i = 0; i < 10; i++) {
    Planet p = new Planet();
    p.setX(0);
    p.setY(0);
    planets.add(p);
}
dotvav
  • 2,808
  • 15
  • 31
1
for(int i=0; i < numOfObjectsToMake; i++){
    Point p = new Point();//make whatever object
    p.x = valX; //set what ever here
    p.y = valY; //set what ever here
    //Problem - im going to lose the object
}

Now at this point you need some way to store the object you have made otherwise the next iteration of the loop is going to replace it.

So in this case I am going to use a list to store it, you might want to consider what type of collection you might want to store it in. Maybe a list a set or even an array would do.

//Make list before so its within scope
ArrayList ls = new ArrayList<Point>();

for(int i=0; i < numOfObjectsToMake; i++){
    Point p = new Point();//make whatever object
    p.x = valX; //set what ever here
    p.y = valY; //set what ever here
    ls.add(p);//Problem solved i have stored the object
}

ls.get(...);//pull out objects later for use
Chris
  • 460
  • 8
  • 16
  • Does ls.add(..) automatically increment or will it replace the last entry? – Tom Haffenden Sep 14 '15 at 10:29
  • Nope a list will hold an infinite (well as many till you run out of memory and crash) amount of objects for you. Yes it index's each one so you can pull them back out ie: ls.get(1) I would recommend reading/youtube watching some tutorials on collections and managing objects, its practically how every program manages large amounts of objects. – Chris Sep 14 '15 at 10:32
  • Ok thanks for amazing detailed help, ill defiantly go and watch some video's to understand what it does. – Tom Haffenden Sep 14 '15 at 10:34