ryan
ryan

Reputation: 1

Creating Object inside a loop

I have created a Rectangle class, inside of a for loop I am creating a new Rectangle object each time through the loop. If my understanding is correct, each time a new Rectangle is created, the previously created Rectangle objects are inaccessible (the way the code is currently written) because the reference variable rectangle is now pointing to the most recently created Rectangle object. What is the best way to allow us to have access each and every Object when creating a new Object each time through a loop? I know that one way would be to create a List and add each newly created Rectangle to the list.

public class RectangleTest {

    public static void main(String[] args) {

        for (int i=1;i<5;i++){
            Rectangle rectangle = new Rectangle(2,2,i);
            System.out.println(rectangle.height);
        }
    }
}


public class Rectangle {

    int length;
    int width;
    int height;

    public Rectangle(int length,int width,int height){
        this.length = length;
        this.width = width;
        this.height = height;
    }

}

Upvotes: 0

Views: 4384

Answers (2)

euthimis87
euthimis87

Reputation: 1143

You should create an ArraList or a LinkedList:

public class RectangleTest {
    public static void main(String[] args) { 
       List<Rectangle> listOfRectangles = new LinkedList<Rectangle>();
       for (int i=1;i<5;i++){
         Rectangle rectangle = new Rectangle(2,2,i); 
         listOfRectangles.add(rectangle);
         System.out.println(rectangle.height);
        }  
   }
}


public class Rectangle {

   int length;
   int width;
   int height;

   public Rectangle(int length,int width,int height){
      this.length = length;
      this.width = width;
      this.height = height;
   }

}

Upvotes: 0

Drejc
Drejc

Reputation: 14286

You need to store the created references in some list or array.

List<Rectangle> list = new ArrayList<>();

for (int i=1;i<5;i++){
        Rectangle rectangle = new Rectangle(2,2,i); 

        list.add(rectangle);

        System.out.println(rectangle.height);
    } 


System.out.println(list.get(0).height);

Upvotes: 2

Related Questions