- /**
- * Demonstrates how to
create an array of objects.
- *
- * @author (TK Rogers)
- * @version (1-26-10)
- */
- import
java.util.ArrayList; // Needed for using ArrayLists
- public class
Forrest {
-
-
public static void main ( ) {
-
//the code below creates
and outputs an array of Tree objects. ///////////////////////////
-
//Creates the memory location for an array that can
contain 3 Tree objects.
-
Tree [ ] trees = new Tree [3];
-
-
//This loop creates a
unique Tree object in each memory location of the array.
- for
( int x = 0; x < 3; x++ ) {
-
trees [ x ] = new Tree (x, (int) (Math.random ( ) * 3) ) ;
- }
-
- for
( int z = 0; z < 3; z++ ) {
-
System.out.println ( "tree " + z + ": x = " + trees [z].xpos +
-
", y = " + trees [z].ypos ) ;
- }
-
System.out.println ( ) ;
-
- //the
code below creates and outputs an ArrayList of Tree objects. /////////////////
-
ArrayList <Tree> greenTrees = new ArrayList (3) ;
- for
( int x = 0; x < 3; x++ ) {
-
greenTrees.add (new Tree (x, (int)(Math.random (
)*3) ) ) ;
- }
-
- for
( int z = 0; z < 3; z++ ) {
-
System.out.println ( "greenTree " + z + ": x = " + greenTrees.get (z).xpos +
-
", y = " + greenTrees.get (z).ypos ) ;
- }
- }
- }