I need help with this java programming question?

Posted by admin on February 26th, 2010 and filed under solarsystem | 1 Comment »

I’m suppose to declare and intialize an arrayList of PlanetS with the name solarSystem to represent our solar system. The arrayList sholud contain one element for each planet in our solar system.

ArrayLists can contain any object type, as well as a mixture of object types. As such, populating the ArrayList is easy:

ArrayList solarSystem = new ArrayList();
//create a PlanetS object for Venus
solarSystem.add(/*name of PlanetS object*/);
//create a PlanetS object for Mercury
solarSystem.add(/*name of PlanetS object*/);
//etc etc…

The complexity comes when you want to get data out of the ArrayList, as you will have to cast it to the correct type:

PlanetS p = (PlanetS) solarSystem.get(1);

One Response

  1. Nathanael H Says:

    ArrayLists can contain any object type, as well as a mixture of object types. As such, populating the ArrayList is easy:

    ArrayList solarSystem = new ArrayList();
    //create a PlanetS object for Venus
    solarSystem.add(/*name of PlanetS object*/);
    //create a PlanetS object for Mercury
    solarSystem.add(/*name of PlanetS object*/);
    //etc etc…

    The complexity comes when you want to get data out of the ArrayList, as you will have to cast it to the correct type:

    PlanetS p = (PlanetS) solarSystem.get(1);
    References :
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.