ArrayList issue with adding and for eaches

    public class Test
    {
      public static void main(String[] args)
      {
        String[] lists={"Bob","Sally","Jim","Harry"};

        ArrayList<String> names= new ArrayList<String>();

        for(String x: lists)
        {
            if(names.size()%2==0)
            names.add(x);
        }
        System.out.print(names);    
    }
}

Please tell me how this prints [Bob]

I am beginning computer science arraylists and this confuses me.

When the for each loop is adding why doesnt Jim be added too, since it is at position 2 which being % equals 0

1 answer

  • answered 2018-02-13 01:28 ACVM

    Whenever you encounter a loop problem, you should create a T chart!

    Iteration | Values
    ----------------------------------------------
        0     | x = "Bob"
              | names = {}
              | names.size = 0 | name.size % 2 = 0 
    ----------------------------------------------    
        1     | x = "Sally"
              | names = {"Bob"}
              | names.size = 1 | name.size % 2 = 1
    ----------------------------------------------    
        2     | x = "Harry"
              | names = {"Bob"}
              | names.size = 1 | name.size % 2 = 1
    ----------------------------------------------    
        3     | x = "Sally"
              | names = {"Bob"}
              | names.size = 1 | name.size % 2 = 1
    

    So you can see after iteration 0, "Bob" is added to the names list which means name.size() % 2 is no longer 0, it's now 1! So no more names will ever be added!