Vinay Sharma
Vinay Sharma

Reputation: 1303

how we can increase size of StringBuffer?

I want to set size of my StringBuffer object as per requirement in code.

 StringBuffer sb = new StringBuffer();

 for (List<Integer> l : lists)
 {
   sb.delete(0, sb.length());
   //here i want to set size of sb according to l.size()
 }

I want to set size different on each iteration.

Upvotes: 0

Views: 3094

Answers (1)

Mena
Mena

Reputation: 48444

If you want your StringBuffer to be initialized with the size of your List, just initialize it by passing the size as int:

StringBuffer sb = new StringBuffer(l.size());

Edit

If you need to set your size dynamically, based on the values in your List, you can use the following idiom:

List<Integer> l = new ArrayList<Integer>(Arrays.asList(new Integer[]{1,2,3}));
StringBuffer sb = new StringBuffer();
for (int i: l) {
    sb.setLength(i);
}

Side-note

You don't need to use StringBuffer unless you are mutating it in a multi-threaded context.

You could use StringBuilder instead.

Upvotes: 1

Related Questions