matrix1395
matrix1395

Reputation: 69

Creating a list where each of the list objects will have its own subobjects

I have a list of ConRoShip class ships called 'conRoShipList'. I would like to have several containers of BasicContainer class on each of these ships from the list that I create as objects. How to place BasicContainer objects inside the ConRoShip object that will be in conRoShipList? I would like to have ,for example, 5 containers on one ship that will be on the list. Below codes:

public
    class ConRoShip  extends Ship {

    private final float MAX_SHIP_WEIGHT_CAPACITY = 15000.00f;
    private float initialShipCapacity = 2000.00f;

    List<ConRoShip> conRoShipList = new LinkedList<ConRoShip>();

    public ConRoShip(String name, String homePort, String transportSourceLocation, String transportDestination) {
        super(name, homePort, transportSourceLocation, transportDestination);
        shipCapacity += initialShipCapacity;
    }

}

public
    class BasicContainer extends Container {

    private int cargoCapacityUnits; // pieces

    public BasicContainer(String name, String sender, String safety,
                          double netWeight, double grossWeight, int cargoCapacityUnits) {
        super(name, sender, safety, netWeight, grossWeight);
        this.cargoCapacityUnits = cargoCapacityUnits;
    }
}

Upvotes: 0

Views: 156

Answers (2)

WJS
WJS

Reputation: 40034

I recommend using a map in the ship class.

Map<String, List<Container>> containers = new HashMap<>();

Then containers can be added as follows. This automatically creates a new list for each named container and then adds the container to that list.

containers.computeIfAbsent(name, k -> new ArrayList<>())
                .add(container);

you could have an add method as follows:

public void add(String containerName, Container c) {
    containers.computeIfAbsent(containerName, k -> new ArrayList<>())
                .add(c);
}

Retrieve the list of containers.

public List<Container> getContainer(String containerName) {
    return containers.get(containerName);
}

Upvotes: 1

Sascha
Sascha

Reputation: 87

You can add an ArrayList of BasicContainers to the constructor. So everytime u are creating a ConRoShip there will be the possibility to add all the containers u want to this object.

public ConRoShip(String name, String homePort, String transportSourceLocation, String 
transportDestination, ArrayList<BasicContainer> basicContainerList) {
    super(name, homePort, transportSourceLocation, transportDestination);
    shipCapacity += initialShipCapacity;
}

Upvotes: 0

Related Questions