-2

I'm trying to initialize a StringBuilder with "". These are 2 samples, the first one doesn't work while the second one works. Can anyone explain a bit more? Is this because StingBuilder is an object?

    for (StringBuilder element : sb){
        element = new StringBuilder(""); 
    } // this solution doesn't work, print sb[0] = null

    for(int i=0; i<sb.length; i++){
        sb[i] = new StringBuilder("");
    }

I'm expecting both would work.

4
  • 1
    Define "works". What are you trying to accomplish? What is sb? Please show a complete code example that we can copy/paste, compile, and run ourselves without any additional errors than what you are asking about. This means you need to declare all variables that you use and include valid System.out.println() calls rather than just a comment. Commented Aug 14, 2023 at 23:27
  • Also, if your question is about arrays, maybe you should do something simpler like an int[] to illustrate what you are doing rather than a StringBuilder[]. Commented Aug 14, 2023 at 23:27
  • 3
    Your first loop pulls an element from the array, then assigns the variable a new reference, so element now points to somewhere else, not what's in the array. The second assigns the reference to the array element directly Commented Aug 14, 2023 at 23:32
  • Does this answer your question? Why doesn't assigning to the iteration variable in a foreach loop change the underlying data? Commented Sep 8, 2023 at 1:47

2 Answers 2

1

The for-each loop hides the iterator, so your first approach will not work. Another solution would be generating a Stream<StringBuilder> and then converting that to an array. Assuming you want an array of n StringBuilder(s) that might look something like,

StringBuilder[] sb = Stream.generate(() -> new StringBuilder()).limit(n)
        .toArray(size -> new StringBuilder[size]);

Note that a forEach loop over the array indices would also work

IntStream.range(0, sb.length).forEach(i -> sb[i] = new StringBuilder());
Sign up to request clarification or add additional context in comments.

Comments

1

This answer is super helpful and explains in detail about what element actually is in your first for-each loop. It's an instance of an iterator, not the actual member of the StringBuilder array sb.

Your second approach works because you are populating individual array elements sb[i] with value "".

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.