Search code examples
javafor-loopauto-generate

The best way to generate multiple version of 1 object JAVA


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.


Solution

  • 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