• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

Reuse Object

 
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 227
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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());
 
Eliminate 95% of the weeds in your lawn by mowing 3 inches or higher. Then plant tiny ads:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic