Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Arrays and objects

 
Laura Arnold
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do I create an array of objects?
For example I have a class that makes a rectangle. I am using another applet class to draw the rectanfgle to the screen. I'm trying to create an array of rectangle objects to make multiple rectangles on the screen. Thanks for your help.
 
Allen Alchian
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following would create an array, called polygons, of six references to objects of type Rectangle...
//create references to Rectangle objects
Rectangle rec1, rec2, rec3, ...
// create your array, called polygons
Rectangle polygons[] = new Rectangle[6];
// now assign rectangle objects to
// each array element...
polygons[1] = new rec1;
polygons[2] = new rec2;
...

[This message has been edited by Allen Alchian (edited November 25, 2000).]
[This message has been edited by Allen Alchian (edited November 25, 2000).]
 
Laura Arnold
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your help. When I try to do this, I keep getting a syntax error saying that another [] is expected in the line:
polygons[1] = new rect1;
 
Kalidas Pavi
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Laura,
try this
// initialize the rectangle objects after creating array and // rectangle objects as mentioned by Allen
rec1 = new Rectangle ( 20,30,40,50);
rec2 = new Rectangle ( 40,40,40,50);
.....
// assign the rectangle objects to the array elements.
// here the new is not required.
polygons[1] = rec1;
polygons[2] = rec2;
Hope this helps (and compiles properly!).
Kalidas.
 
Allen Alchian
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Kalidas.
 
Laura Arnold
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you both for all your help!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic