0

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.

  • 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. – Code-Apprentice Aug 14 '23 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[]`. – Code-Apprentice Aug 14 '23 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 – MadProgrammer Aug 14 '23 at 23:32

2 Answers2

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());
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
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 "".