0

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.

3
  • 1
    Hint: try reading the Javadoc that comes with classes like docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html . Of course, it is nice for people answering your question to pimp their reputation; but besides that there is really no benefit to the community by asking something that trivial.In addition: consider using a StringBuilder instead of StringBuffer. Commented Apr 28, 2015 at 9:28
  • I know that it is trivial type question but it has good thing to know how it is possible to do this. Because there no any method in StringBuffer class itself. Commented Apr 28, 2015 at 9:35
  • Well, what are you expecting? A StringBuffer can be created with a given capacity; and the javadoc tells you: "ah, right, the capacity can not be changed later on". Now what kind of answer do you expect when asking for "how can I change the capacity?" ... other people can't magically add such methods to the class. Besides: why are you worried about the capacity at all? Are you dealing with millions of list elements; and the need to micro-optimize your code therefore? Commented Apr 28, 2015 at 9:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

StringBuilder is also same not have any option to increase size
if we call this method then it will add blank spaces in buffer and if we append other string then that string will be added after that space.
same is with StringBuilder, that class is not having any specific method to define size.
@VinaySharma the "specific method to define size" is setLength. Not sure it does what you want it to - here's the link to the API. Not really sure what you want it do to on the other hand...
@Mena setLength does not change the capacity of the buffer.
|

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.