Need some help regarding arraylist
Hi,
ArrayList arrL = new ArrayList();
ArrayList tmpArrL = new ArrayList();
for (int i = 0; i < size; i++) {
Character ch = new Character(text.charAt(i));
arrL.add(ch);
}
tmpArrL = arrL;
;
;
String newText = "";
for (int i = 0; i < arrL.size(); i++) {
newText += tmpArrL.get(i);
}
return newText;
In some cases the arraylist contains around 500000 characters. in this situtation tool gets hanged and it takes alot of time to execute the for loop.
Please let me know how to handle this situation.
Thanks,
Sarayu.
Look up the class StringBuffer
Pay attention to the routine toString()
Use that instead of ArrayList, either through entire operation, or just at the end when you could convert your ArrayList to a StringBuffer
Your problem is that Strings are immutable. When you add a single character to a string, as you are doing to newText, the entire previous string, must be copied to a new place that is slightly larger and the extra character added to this new String. Then the old string is marked for garbage collection.
As you approach 500000 characters, for each new character you add, you must allocate a new half meg of character space, copy half a meg of characters, and then dispose of old half a meg. This is thrashing your garbage collector and is a total waste of time.
Learn about StringBuffers
> Hi,
>
> ArrayList arrL = new ArrayList();
> ArrayList tmpArrL = new ArrayList();
>
> for (int i = 0; i < size; i++) {
>Character ch = new Character(text.charAt(i));
> arrL.add(ch);
> }
> tmpArrL = arrL;
> ;
> ;
> String newText = "";
> or (int i = 0; i < arrL.size(); i++) {
>newText += tmpArrL.get(i);
> return newText;
>
> In some cases the arraylist contains around 500000
> characters. in this situtation tool gets hanged and
> it takes alot of time to execute the for loop.
>
> Please let me know how to handle this situation.
>
> Thanks,
> Sarayu.
Why are you using ArrayList in the first place