Home > Software engineering >  When Java StringBuilder appends character '0', is it treated as normal character or end of
When Java StringBuilder appends character '0', is it treated as normal character or end of

Time:07-14

I'm using jdk 1.8 on win10 and I've made a test:

    public static void main(String[] args) {
        char buf[] = {'1', '1', '0', '0'};
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buf.length;   i) {
            sb.append(buf[i]);
        }
        System.out.println("case1: 0 as normal character : "   sb.toString());

        StringBuilder sb2 = new StringBuilder();
        Deque<Integer> di = new ArrayDeque<>();
        di.add(1);
        di.add(1);
        di.add(0);
        di.add(0);
        for (int i = 0; i < di.size();   i) {
            sb2.append(di.pollFirst() == 1 ? '1' : '0');
        }
        System.out.println("case2: 0 as end of string : "   sb2.toString());
    }

It prints:

case1: 0 as normal character : 1100
case2: 0 as end of string : 11

Why the 2 cases gives different results?

CodePudding user response:

You loop while i is less than di.size(), but every time around the loop you increment i by 1 and remove one item from the deque, decreasing its size.

After two iterations of the loop, i == 2 and di.size() == 2 and i < di.size() is false. So only two numbers are added to the StringBuilder.

CodePudding user response:

The behavior you see has nothing to do with strings. It has to do with how you're consuming the deque. Look at this code:

Deque<Integer> di = new ArrayDeque<>();
di.add(1);
di.add(1);
di.add(0);
di.add(0);

for (int i = 0; i < di.size();   i) {
    sb2.append(di.pollFirst() == 1 ? '1' : '0');
}

What happens in the for-loop?

Start of iteration 0:  i = 0;  di = [1, 1, 0, 0];  di.size() == 4.
Start of iteration 1:  i = 1;  di = [1, 0, 0];     di.size() == 3.
Start of iteration 2:  i = 2;  di = [0, 0];        di.size() == 2.
But (i < di.size()) == false, so the loop ends.

Hence, you should change your loop to the following:

while (!di.isEmpty()) {
    sb2.append(di.pollFirst() == 1 ? '1' : '0');
}

And now sb2 will have the same text as sb.

CodePudding user response:

after every pool size is decreasing by 1, so your loop in iterating 2 times. you can do this:

for ( int p:di ) {
           sb2.append(p);
       }
       di.clear();
       System.out.println("case2: 0 as end of string : "   sb2.toString());

Or

while (!di.isEmpty()) {
    sb2.append(di.pollFirst() == 1 ? '1' : '0');
}
  • Related