Is there some ways how I could clone StringBuilder ? I am reading files by bits then convert these bits to ASCII chars after that I collect chars into String builder and when I have for example 8 chars I put that String Builder object into Array List. Then I clean it and again do the same. However I can’t create new string builder because of memory and I can’t do changes to that String builder because in Array List also that builder changes.
So I think I have to clone that String Builder and put it into Array List. There is just one problem String Builder don’t have clone(). So what is my alternatives ?
Maybe someone could give some ideas what is neat way to do this considering about performance and memory.
ArrayList characters = new ArrayList();
int counter = 0;
StringBuilder sb = new StringBuilder(blockSize-1);
while (mbb.hasRemaining()) {
char charAscii = (char)mbb.get();
counter++;
charCounter++;
if (counter == blockSize){
sb.append(charAscii);
characters.add(sb);//sb.toString()
sb.delete(0, sb.length());
counter = 0;
}else{
sb.append(charAscii);
}
if(!mbb.hasRemaining()){
characters.add(sb);
}
}
fc.close();
return characters;
If you don’t have the memory to create a new
StringBuilder, then you don’t have the memory to create a newStringBuilder, and cloning wouldn’t change that. The only real way to copy aStringBuilderisnew StringBuilder(myBuilder), or something equivalent.If you’re getting
OutOfMemoryException, you’ll need to either get more memory, or find some other way to reduce memory consumption.