0

I am interested in concatenating a string to elements of an arraylist while iterating.When I run the below code,I am getting a ConcurrentModificationException.My code is:

ArrayList<String> list=new ArrayList<String>();
list.add("000);
list.add("00");
list.add("0");
for(String s:list)
{
    if(s.length()==1)
    {
        String s2="000" + s;
        list.add(s2);

    }


    if(s.length()==2)
    {
        String s2="00" + s;

    }


    if(s.length()==3)
    {
        String s2="0" + s;
    }
}

My question is how to add the concatenated strings back to list without using StringBuilder as when I use a StringBuilder,it is causing other parts of my program to malfunction? So just need some guidance.

  • 1
    The code you've given will *not* cause an exception. Please provide a short but complete program *that demonstrates the problem*, as well as telling us what you're trying to achieve. – Jon Skeet Nov 05 '14 at 18:02
  • I changed it.Plz see now – Java_stack1 Nov 05 '14 at 18:04
  • You still haven't explained what you're trying to achieve. – Jon Skeet Nov 05 '14 at 18:06
  • What I want to do is if my arraylist contains a binary string "00",I want to represent 4 bits for the number.So "00" will become "0000".Similarly,if it contains "0" it should have 3 zeroes appended to the front.In short, all my strings should come out having a length of 4.Hope this helps – Java_stack1 Nov 05 '14 at 18:09
  • Your question is confusingly worded. You don't want to add elements to the list, you want to prepend characters to the Strings contained within your list. – Sean Bright Nov 05 '14 at 18:21
  • In future, you should put the details in the *question* - not just in comments. – Jon Skeet Nov 05 '14 at 19:00

7 Answers7

1

I would just use List.set:

List<String> list = new ArrayList<String>();

list.add("000");
list.add("00");
list.add("0");

for (int i = 0; i < list.size(); i++) {
    String value = list.get(i);
    list.set(i, ("0000" + value).substring(value.length()));
}
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
0

The exception will occur if you change the contents of the list (i.e. add or remove an element) anywhere in your for loop.

ArrayList<String> list=new ArrayList<String>();
list.add("000);
list.add("00");
list.add("0");
ArrayList<String> itemsToAdd = new ArrayList<String>();  // <======
for(String s:list) {
    if(s.length()==1) {
        String s2="000" + s;
        //list.add(s2);   DONT DO THIS
        itemsToAdd.add(s2);  // DO THIS INSTEAD
    }

    if(s.length()==2) {
        String s2="00" + s;
    }


    if(s.length()==3) {
        String s2="0" + s;
    }
}

// NOW APPEND THE LIST
// This is safe as the iteration is complete.
list.addAll(itemsToAdd.add);
EJK
  • 12,332
  • 3
  • 38
  • 55
0
  1. make a second list
  2. add the new elements to that second list
  3. add all the elements in the second list back into the first one after you're done iterating
  • Thanks.But will this practice retain the order of elements in new list similar to that in original? – Java_stack1 Nov 05 '14 at 18:18
  • @RabiaMairaj it depends on how you implement it, but if you implement it in the most straightforward way, the elements will be added in the same order that they would have been added in your method had it worked – Sam I am says Reinstate Monica Nov 05 '14 at 18:57
0

Have a look at this one: Modifying Java ArrayList while iterating over it

Short story: Java won't let you change a list that you're iterating over. Instead, make a copy by putting the list to be cloned into the new arraylist's constructor arguments and then change the new list:

ArrayList<String> list=new ArrayList<String>();
list.add("000);
list.add("00");
list.add("0");
ArrayList<String> listSecond =new ArrayList<String>(list);

for(String s:list)
{
    if(s.length()==1)
    {
        String s2="000" + s;
        listSecond.add(s2);

    }...
Community
  • 1
  • 1
FelixMarcus
  • 380
  • 3
  • 14
0

Your list.add(s2) is a problem. You just can't play with lists while iterating (well with an iterator you can delete items). Here's a possible solution:

    ArrayList<String> list=new ArrayList<String>();
    list.add("000");
    list.add("00");
    list.add("0");
    List<String> newOnes = new ArrayList<>();
    for(String s:list)
    {
        if(s.length()==1)
        {
            String s2="000" + s;
            newOnes.add(s2);

        }


        if(s.length()==2)
        {
            String s2="00" + s;

        }


        if(s.length()==3)
        {
            String s2="0" + s;
        }
    }
    list.addAll(newOnes);
SteveS
  • 536
  • 1
  • 6
  • 10
0

create a tempList and add the element to tempList and at last assign tempList to list

public static void main (String[] args) throws Exception
    {
            ArrayList<String> list=new ArrayList<String>();
            ArrayList<String> tempList=new ArrayList<String>();
            list.add("000");
            list.add("00");
            list.add("0");

            for(String s:list)
            {
                if(s.length()==1)
                {
                    String s2="000" + s;
                    tempList.add(s2);

                }


                if(s.length()==2)
                {
                    String s2="00" + s;
                    tempList.add(s2);

                }


                if(s.length()==3)
                {
                    String s2="0" + s;
                    tempList.add(s2);
                }
            }
            list=tempList;
            System.out.println(list);

        }
Rustam
  • 6,485
  • 1
  • 25
  • 25
0

Modifying your list while iterating: (more generic and short)

        ArrayList<String> list= new ArrayList<>();
        String zeros = "00000000";
        list.add("000");
        list.add("00");
        list.add("0");
        for(int i=0;i<list.size();i++) {
            String s = list.get(i) + zeros.substring(0,4-list.get(i).length());
            list.set(i,s);
        }           
        for (String s : list)
            System.out.println(s);
SkyMaster
  • 1,323
  • 1
  • 8
  • 15