user3887792
user3887792

Reputation: 81

How can you print multiple ArrayLists next to each other

I have an arraylist of an Object I called Process and each process has an arrayList of integers for allocation, max and need, so each process essentially has 3 arraylists to it. I am trying to make a table that looks like this

              Allocation       Max           Need
 Process 1    1 2 3 4          1 2 3 4     1 2 3 4 
 Process 2    5 7 8 9          5 7 8 9     5 7 8 9 
 Process 3    1 2 3 4          1 2 3 4     1 2 3 4 
 Process 4    5 7 8 9          5 7 8 9     5 7 8 9 

etc each number is it's own slot so the size of all of the arrays of is 4. This is my code I am trying

 public String toString() {
    String temp = "";
    String tempAllo = "";
    String tempMax = "";
    String tempNeed = "";

    for (int j = 0; j < allocation.size(); j++) {
        tempAllo = allocation.get(j).toString() + " ";
        tempMax = max.get(j).toString() + " ";
        tempNeed = need.get(j).toString() + " ";
    }

    temp = id + "\t" + tempAllo + "\t" + tempMax + "\t" + tempNeed + "\n";

    return temp;
}

but it prints out

                   Allocation       Max           Need
     Process 1        4             4              4 
     Process 2        9             9              9 
     Process 3        4             4              4
     Process 4        9             9              9 

so it is only printing out the last one. Thank you in advanced for the help

Upvotes: 1

Views: 768

Answers (2)

BatScream
BatScream

Reputation: 19700

It should be: (note the +=)

tempAllo += allocation.get(j).toString() + " ";
tempMax += need.get(j).toString() + " ";
tempNeed += allocation.get(j).toString() + " ";

I would suggest you to use a StringBuilder for variables temp, tempAllo,.. instead of a String.

So that you could do,

tempAllo.append(allocation.get(j).toString()).append(" ");

Upvotes: 3

Shahzad
Shahzad

Reputation: 2073

try:

for (int j = 0; j < allocation.size(); j++) {
    tempAllo = tempAllo.concat(allocation.get(j).toString() + " ");
    tempMax = tempMax.concat(need.get(j).toString() + " ");
    tempNeed = tempNeed.concat(allocation.get(j).toString() + " ");
}

Upvotes: 0

Related Questions