in Java, I am creating a class, and I would like to keep track of all objects the are created in this class. I have implemented a way to store the names of each object (using ArrayList), but I cannot figure out how to store the object itself in the ArrayList. Here is a snippet of my code:
static public class Ship {
private static ArrayList<String> ships = new ArrayList<String>();
private static ArrayList<Ship> shipObs = new ArrayList<Ship>();
String name;
private ArrayList<String> cruises = new ArrayList<String>();
int maxPassengers;
private static final String[] CABINS = new String[] {"Balcony", "Ocean View", "Suite", "Interior"};
private int[] passengers = new int[] {0,0,0,0};
boolean inService = false;
public Ship(String name, int maxPassengers) {
// Ensure that each ship has a unique name
if (ships.size() == 0) {
this.name = name;
ships.add(name);
}
else if (ships.size() >= 1) {
for (int i=0; i < ships.size(); i++) {
if (ships.get(i).equals(name)) {
System.out.println("Ship "+name+" cannot be created because that name already exists");
return;
}
}
this.name = name;
ships.add(name);
}
this.maxPassengers = maxPassengers;
As you can see, I have the static ArrayList that I would like to populate with all created ships. I assume that this population would take place in the initializing function, but the only method for doing so that I can see would to do something like
shipObs.add(this);
But that doesn't work...