How do you print out objects of a list within a list?

82 views Asked by At

I'm trying to solve a version of a bin packing problem called the Truck Loading Problem. Here's a snippet of my code so far:

public class Truck {

  private List<Stack> stacks = new ArrayList<Stack>();

  ...


  public String toString(){
    String stringToReturn = "";
    for(Stack st : stacks){
        stringToReturn = stringToReturn + st.toString();
    }

    return String.format("%s\n", stringToReturn);
  }
}

public class Stack {

  private List<Box> boxes = new ArrayList<Box>();

  ...

  public String toString(){
    String stringToReturn = "";
    for(Box b : boxes){
        stringToReturn = stringToReturn + b.toString() + ", ";
    }
    return String.format("%s\n", stringToReturn);
  }
}

public class Box {

  @Override
  public String toString(){
    return String.format("H: %d, W: %d | ", getHeight(), getWidth());
  }

public class Loader{
  static List<Truck> trucks = new ArrayList<Truck>();

  public static void printTrucks(List<Truck> trucks){
    int counter = 1;
    for(Truck t : trucks){
        if(t.getStacks().size() != 0){
            System.out.printf("Truck %d:\n", counter);
            t.toString();
            counter++;  
        }
    }
  }
}

So as you can see, I have three Objects; a Truck, a Stack (ie a stack of boxes not the data structure) and a Box. A Stack stores a list of boxes currently in the stack. A Truck stores a list of Stacks it has. So this is what I want to be able to do; for each truck with something in it, print out any stacks and any boxes in those stacks. An example output I'm trying to achieve would be this:

Truck 1:
Stack 1: H: 1, W: 4 | H: 2, W: 2
Stack 2: H: 4, W: 4

Truck 2:
Stack 1: H:3, W: 6

Currently all I print out is:

Truck: 1
Truck: 2
etc.

For some reason the stringToReturn doesn't appear to be working in the way I'm thinking. Can anyone provide some help with this please? I'm aware my code doesn't follow the example I want but I still don't see why no information on the boxes is not being displayed.

1

There are 1 answers

2
Andrew Coates On

Turns out I got tunnel vision and completely missed the fact I called t.toString() then did nothing with it. Just needed to print it out. Silly me.