2017-08-08 41 views
1

我想借ArrayList中的每個元素,並用它來創建一個字符串是:打印ArrayList中的每個元素,並用它在字符串的Java

  1. 包含儘可能多的單詞,並
  2. ArrayList中的元素
  3. 爲每個單詞打印來自ArrayList的int值。

這樣可以很清楚我想打印一個String,它看起來就像這樣:

System.out.println(result); 
element(0), element(1), element(2), element(3) 

不幸的是,我只得到從ArrayList中的最後一個整數的價值,但數量「元素」的話是正確的,所以我的實際結果字符串看起來像這樣:

System.out.println(result); 
element(3), element(3), element(3), element(3) 

ArrayList中只有4個要素:

[0, 1, 2, 3] 

爲了產生這種不正確的字符串我用下面的代碼:

List<Integer> intList = new ArrayList<Integer>(); 
int intValue; 
String result; 

int n = intList.size(); 
for (int i=0; i < n; i++) { 
    intValue = intList.get(i); 
    result = String.join(", ", java.util.Collections.nCopies(n, "element("+intValue+")")); 
} 

所以,我怎麼能做出與ArrayList中的所有值正確的字符串?

+0

你是否已經通過調試器完成了這一步/ – ja08prat

+1

您每次都會覆蓋您的字符串。看看GostCats的答案。您必須追加字符串。 –

回答

2

這裏:

for ... { 
    result = String.join(...) 
} 

在你的循環,你重新分配每次迭代過程中加入了串到你的結果。換句話說:在循環(n)中,你丟棄循環(n-1)中創建的內容。

嘗試使用+ =代替。或者只是與:

StringBuilder builder = new StringBuilder; 
for ... { 
    builder.append(... 
} 
String finalResult = builder.toString(); 

改爲。

作爲使用生成器:

  • 使得你的意圖更加清晰(你打算打造到底一個字符串)
  • 給出了一些輕微的性能改進(這並不真正的問題給出這裏的「小規模」)。
+0

謝謝@GhostCat,兩種方法都很好。 – simtim

+0

非常歡迎您! – GhostCat