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.

[635 byte] By [Sarayu_Geethajalia] at [2007-10-3 4:35:52]
# 1

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

marlin314a at 2007-7-14 22:39:32 > top of Java-index,Other Topics,Algorithms...
# 2
And using the unsynchronized StringBuilder instead of the synchronized StringBuffer might improve performance even further.
horstmeyera at 2007-7-14 22:39:32 > top of Java-index,Other Topics,Algorithms...
# 3
Thanks alot.I solved the problem using string buffer / stringbuilder.
Sarayu_Geethajalia at 2007-7-14 22:39:32 > top of Java-index,Other Topics,Algorithms...
# 4

> 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

kilyasa at 2007-7-14 22:39:32 > top of Java-index,Other Topics,Algorithms...