0

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;
    }

}
3
  • 2
    Use an array / List of Rectangles Commented Oct 16, 2014 at 12:28
  • 1
    What are you trying to achieve by saving the references? a List would be an option, but could be something else if you provide context. Commented Oct 16, 2014 at 12:32
  • I think it's bad placement, if you need something not-local to an actual iteration of the loop, define it outside of it. Commented Oct 16, 2014 at 13:27

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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;
   }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.