Using collections prior to the modern Java platform

Here is an example of how we would create our own collections prior to the modern Java platform. This first class defines the structure for PlanetCollection. It has the following components:

  • A single instance variable
  • A one-argument constructor
  • A mutator/setter method
  • An accessor/getter method
  • A method to print the object

Here is the code that implements the previously listed constructor and methods:

public class PlanetCollection {

// Instance Variable
private String planetName;

// constructor
public PlanetCollection(String name) {
setPlanetName(name);
}

// mutator
public void setPlanetName(String name) {
this.planetName = name;
}

// accessor
public String getPlanetName() {
return this.planetName;
}

public void print() {
System.out.println(getPlanetName());
}
}

Now, let's look at the driver class that populates the collection:

import java.util.ArrayList;

public class OldSchool {

private static ArrayList<PlanetCollection>
myPlanets = new ArrayList<>();

public static void main(String[] args) {
add("Earth");
add("Jupiter");
add("Mars");
add("Venus");
add("Saturn");
add("Mercury");
add("Neptune");
add("Uranus");
add("Dagobah");
add("Kobol");

for (PlanetCollection orb : myPlanets) {
orb.print();
}
}

public static void add(String name) {
PlanetCollection newPlanet =
new PlanetCollection(name);
myPlanets.add(newPlanet);
}
}

Here is the output from this application:

OldSchool class output

This code is, unfortunately, very verbose. We populated our collection in static initializer blocks instead of using a field initializer. There are other methods for populating our list, but they are all more verbose than they should have to be. These other methods have additional problems, such as the need to create extra classes, the use of the obscure code, and hidden references.

Now, let's take a look at the solution to this problem, which is provided by the modern Java platform. We will look at what is new in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset