YourDoom YourDoom - 1 year ago 90
Java Question

Java - how to find a letter in a string in ArrayList the duplicate string

I have a problem with some tasks. I have to find words that contains letter "r" and duplicate these words. I tried to do this with for loop:

for(int i = 0; i < list.size(); i++){
if(list.get(i).contains("r")){
list.add(list.get(i));
}


But it doesnt work at all. When i add new element to array would it make it bigger? Then list.size will change and loop wont manage to get to the last element of array? Also duplicated word should be just after the original one, for example input:

show
ram
cat

output:

show
ram
ram
cat

Really i have no idea how to duplicate it.

This also doesnt work:

for(int i = 0; i < list.size(); i++){
if(list.get(i).contains("r")){
list.add(i+1, list.get(i));
}

Answer Source

After adding duplicate for element which contains letter r, you would eventually move to that duplicate and since it also contains r you will add duplicate for it, and then after visiting that another copy you will add another duplicate for it, and so on... infinitely so your loop will not end (until you will run of memory).

To avoid it, after duplicating element you need to jump to next element after that duplicate. You can do it by additional incrementing i after

list.add(i+1, list.get(i));
i++;

or

list.add(++i, list.get(i));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download