Preview

19 - Developing Algorithms Using ArrayLists

 1. What code is required (fill in the blanks) to insert Steve into the fourth position?
import java.util.*;  
class JavaExample{  
   public static void main(String args[]){  
      ArrayList alist=new ArrayList();  
      alist.add("Steve");
      alist.add("Tim");
      alist.add("Lucy");
      alist.add("Pat");
      alist.add("Angela");
      alist.add("Tom");
  
      //displaying elements
      System.out.println(alist);
  
      //Adding "Steve" at the fourth position
      _____________________________
  
      //displaying elements
      System.out.println(alist);
   }  
}

  alist.insert(4,"Steve");

  alist.add(3, "Steve");

  alist.add(4,"Steve");

  add(4, "Steve")alist;

 2. What will print when the following code is run?
List numList = new ArrayList();
numList.add(new Integer(1));
numList.add(new Integer(2));
numList.add(new Integer(3));
numList.set(2,new Integer(4));
numList.add(1, new Integer(5));
numList.add(new Integer(6));
System.out.println(numList);

   [1, 2, 3, 4, 5]

   [1, 5, 2, 4, 6]

   [1, 2, 4, 5, 6]

  [1, 2, 5, 4, 6]

 3. What is the output of the following code when executed?
import java.util.*;

public class ArrayListLoop
{
 public static void main(String[] args)
 {
   ArrayList arr = new ArrayList();
   for(int i=1; i < 5; i++)
   {
      arr.add(i);

   }
   for(int i=0; i < arr.size(); i++)
   {
      if (i % 2 == 1)
      {
         System.out.println("Removing element " + i + " : " + arr.get(i));
         arr.remove(i);
      }
   }
   System.out.println(arr);
 }
}

  [1,2,4]

  [1,2,3]

  [1,3]

  [1,3,,4]

 4. Which statement best describes the following code?
import java.util.*;

 public class ParallelTests
 {
     public static void main(String[] args)
     {
         ArrayList test1Grades = new ArrayList();
         ArrayList test2Grades = new ArrayList();
         test1Grades.add(100);
         test2Grades.add(100);
         test1Grades.add(80);
         test2Grades.add(70);
         test1Grades.add(70);
         test2Grades.add(90);
         double total = 0;
         for (int i = 0; i < test1Grades.size(); i++)
         {
             total +=  test1Grades.get(i) + test2Grades.get(i);
         }
         int numberOfGrades = test1Grades.size() * 2;
         System.out.println("Average over two tests: " + total/numberOfGrades);
     }
 }

  The code iterates through two different ArrayLists that hold the same data.

  The code uses a single loop to duplicate an ArrayList that contains similar data.

  None of the options here are correct or adequately explain the code.

  The code traverses two parallel ArrayLists that hold the grades for different tests.