[CSC 204] Example of Creating an Array of Objects

Andrew J. Pounds pounds_aj at mercer.edu
Fri Nov 7 14:15:49 EST 2014


Alright -- so I am getting questions about how one could build an array 
of objects.   There was an example of such a thing on your last quiz.  I 
am going to start there.

Lets say that we are going to make an object called Card.   The java 
class file to define this is below...

public class Card{

    String value;
    String suit;

    public Card() { }  // Zero argument constructor

    public Card( String value, String suit ){
       this.value = value;
       this.suit  = suit;
    }

    public String toString(){
       return String.format("%2s%1s", value, suit);
    }
}


Notice, this class has NO MAIN, but it does have two instance variables, 
two constructors, and one method (a toString method).

Let me know build the class file that has the main program...

import java.util.Arrays;

public class FillDeck{

    public static void main( String argv[]){

    Card[] deck = new Card[0];

    String[] values = {"A", "2", "3", "4", "5", "6", "7", "8", "9", 
"10", "J", "Q", "K"};
    String[] suits = {"C", "S", "D", "H"};

    for (int i=0; i<suits.length; i++) {
      for (int j=0; j<values.length; j++) {
         deck = Arrays.copyOf( deck, deck.length+1);
         deck[deck.length-1] = new Card( values[j], suits[i]);
      }
    }

    System.out.println(deck.length);
    for (Card card : deck ) System.out.println(card);
}
}


I've done some interesting stuff here.   I made an array of type Card 
with no elements in it.  I then added elements to the array (called 
deck) by first enlarging the array and then adding the Card object which 
I created by using the constructor from the Card class.

You could use this same type of methodology to create you array of 
StationData assuming that you have a class defined that holds the 
instance variables for the stationID and state.


-- 
Andrew J. Pounds, Ph.D.  (pounds_aj at mercer.edu)
Professor of Chemistry and Computer Science
Mercer University,  Macon, GA 31207   (478) 301-5627
http://faculty.mercer.edu/pounds_aj



More information about the csc204 mailing list