如何将多个ArrayLists彼此相邻打印

时间:2014-11-12 22:54:04

标签: java arraylist

我有一个Object的arraylist我称为Process,每个进程都有一个用于分配,max和need的整数arrayList,所以每个进程基本上都有3个arraylists。我正在尝试制作一个看起来像这样的表

              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 

等 每个数字都是它自己的插槽,所以所有数组的大小都是4.这是我正在尝试的代码

 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;
}

但打印出来

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

所以它只打印出最后一个。感谢您提前获取帮助

2 个答案:

答案 0 :(得分:3)

应该是:(注意+=

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

我建议您使用StringBuilder表示变量temptempAllo,...而不是String

所以你可以这样做,

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

答案 1 :(得分:0)

尝试:

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() + " ");
}