Search code examples
javalistcomputer-science

Java instantiated and initialized list (Explanation needed)


Could someone help me understand why the answer to this is (B)?

private List<String> animals;
public void manipulate()
{
    for (int k = animals.size() - 1; k > 0; k--)
    {
      if (animals.get(k).substring(0, 1).equals("b"))
      {
        animals.add(animals.size() - k, animals.remove(k));
        }
    }
} 
 

Assume that animals has been instantiated and initialized with the following contents. ["bear", "zebra", "bass", "cat", "koala", "baboon"] What will the contents of animals be as a result of calling manipulate ?

(A) ["baboon", "zebra", "bass", "cat", "bear", "koala"]
(B) ["bear", "zebra", "bass", "cat", "koala", "baboon"]
(C) ["baboon", "bear", "zebra", "bass", "cat", "koala"]
(D) ["bear", "baboon", "zebra", "bass", "cat", "koala"]
(E) ["zebra", "cat", "koala", "baboon", "bass", "bear"] 

Solution

  • on first iteration,

    K=5  
    Baboon is added to index (6 - 5), you get (D)  
    

    second iteration,

    K=4, element is cat
    nothing happens.  
    

    third iteration,

    K=3, element is bass
    bass is added to index (6-3), gets added to its own index, remains (D)  
    

    fourth iteration,

    K=2, element is zebra
    nothing happens. 
    

    fifth iteration,

    K=1, element is baboon
    baboon is added to index (6-1) which is its original index, you get (B)
    

    sixth iteration,

    K=0. there is no iteration as condition k>0 is not fulfilled.