Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Beginner / Object Creation

 
ed jones
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

my goal is to create say 100, small fillable rectangles

if I put, inside a "for" loop

GRect myRect = new GRect( .........etc

I can create the rectangles

my question is,is this correct, ie: should each rectangle be a "new" GRect, or is there a way to just make copies of the first GRect?

thanks
 
Campbell Ritchie
Sheriff
Posts: 48641
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you can create 100 Rectangles by saying new inside a for loop.
Copying is likely to be more complicated than simply writing new.

There is a problem here, however; you are declaring and creating the Rectangle in the same statement inside the loop. Unless you have a reference to attach the Rectangle to (eg a Rectangle[]), in which case the declaration is unnecessary, your Rectangles will go out of scope at the end of the loop and vanish into cyber-limbo never to be seen again!

Another thing lots of people try (instead of copying) is something like this rect2 = rect1;. Try it and see what happens to rect2 when you fill rect1.
 
Don Solomon
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
check-out the flyweight pattern. just depends on what you are doing with the objects.
 
Mohamed Sanaulla
Saloon Keeper
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
my question is,is this correct, ie: should each rectangle be a "new" GRect, or is there a way to just make copies of the first GRect?


Creating a copy of the object is slightly complicated where in one has to override the clone method and use it for creating a copy. Actually there are two versions: One is to use another reference variable to point to the object created in which case its not copying and the other version is a new reference variable pointing to the clone object.

In your loop as and when you create Rectangle objects they are eligible for garbage collection after the end of the each iteration because there is no reference to access the object as the same reference will now be pointing to the new object on the heap.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic