1

I would like to take each element of ArrayList and use it to create a String that:

  1. contains as many words as elements of the ArrayList and,
  2. the int value from the ArrayList is printed for each of the words.

To make it clearer I want to print a String that will look like this:

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

Unfortunately, I'm only getting the value of the last Integer from the ArrayList, but the number of 'element' words is correct, so my actual result String looks like that:

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

The ArrayList has only 4 elements:

[0, 1, 2, 3]

To produce this incorrect String I'm using the following code:

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

So how can I make a correct String with all values of the ArrayList?

2
  • have you stepped through this with the debugger/ Commented Aug 8, 2017 at 13:18
  • 1
    You overwrite your String each time. Look at GostCats answer. You must append the string. Commented Aug 8, 2017 at 13:18

1 Answer 1

2

Here:

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

Within your loop you re-assign that joined string to your result during each iteration. In other words: in loop (n) you throw away what was created in loop (n-1).

Try using += instead. Or just go with:

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

instead.

As using a builder:

  • makes your intent more clear (you intend to build one string in the end)
  • gives some slight performance improvements (which do not really matter given the "small scale" here).
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.