Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Reuse Object  RSS feed

 
Ajai
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I have one requirement which can be explained by the following code snippet.
ArrayList v1= new ArrayList();
StringBuffer sb= new StringBuffer();

for(int i=0;i<10;i++)
{
//sb= new StringBuffer();
sb.append(i);
v1.add(sb);
}

for(int i=0;i<v1.size();i++)
{
System.out.println("v1 "+v1.get(i));
}
The above statement prints "v1 0123456789" each time (as Vector references the same object )unless I uncomment the line in the above code which creates new StringBuffer.Can I reset this stringBuffer somehow instead of creating new StringBuffer and achieve the desired result.
Thanks,
Buggi
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No - if you want to have different objects in the list, you need to create different objects, obviously.
BTW, in the given snippet, using StringBuffer doesn't buy you anything - just use a String instead.
 
Dana Hanna
Ranch Hand
Posts: 227
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not forget the StringBuffer and use

It'll do what you are looking for (why you are looking to do this is your own perogitive).
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or maybe the objective was to get a set of Strings:
1
12
123
1234
etc.
In this case, just replace
v1.add(sb);
with
v1.add(sb.toString());
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!