[英]How to print a 2D array with varying sized cells?
我有一個二維數組,其中每個單元格是一個集合。 每組中都有一個不同的大小,例如從0到5。
我想以易於閱讀的格式打印出二維數組。
例
HashSet<String>[][] schedule = (HashSet<String>[][]) new HashSet[3][5];
schedule[0][0].add("A");
schedule[0][0].add("B");
schedule[0][0].add("C");
schedule[0][2].add("D");
schedule[0][2].add("E");
schedule[1][0].add("F");
schedule[1][1].add("G");
schedule.print();
將產生
-----------------
| A | | D | | |
| B | | E | | |
| C | | | | |
-----------------
| F | G | | | |
-----------------
| | | | | |
-----------------
顯然沒有'-'和'|',但是您明白了。
我能想到的唯一可行的解決方案是為每個列創建並記住迭代器(因此同時記住5個迭代器)並遍歷每一列,一次輸出一個元素,直到在任何迭代器中都沒有更多元素為止。
一個問題是,在G的情況下,即使第一行第二列中沒有任何值,它也會擴展第二列。 我可以通過用選項卡緩沖每列來解決此問題。
顯然,這種hack不能隨其他列一起擴展,因此我想知道是否有我可能忘記的可愛技巧。
謝謝!
對代碼進行一些修改(您忘了實例化數組中的位置!),您肯定可以打印出鋸齒狀的集。
提示:利用HashSet
隨附的iterator()
方法。 迭代器移到一組對象上,一次返回一個,然后暫停直到再次調用它為止,否則就沒有迭代的余地。 您可以在Wikipedia的Iterator文章中找到有關迭代器的更多信息。
使用此方法,您可以將結果收集在String內的每個HashSet中(以您希望的任何方式),並在最后打印出來。
代碼段:
Iterator first = schedule[0][0].iterator();
Iterator second = schedule[0][2].iterator();
// And so forth
String firstResult = "";
String secondResult = "";
// And so forth
while (first.hasNext()) {
firstResult += first.next() + "\t";
if (!first.hasNext()) {
firstResult += "\n";
}
}
while (second.hasNext()) {
secondResult += second.next() + "\t";
if (!second.hasNext()) {
secondResult += "\n";
}
}
// And so forth
System.out.print(firstResult + secondResult + someResult + anotherResult);
填補空白是讀者的練習。
這樣,結果如下:
A B C
D E
F
G
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.