0% found this document useful (0 votes)
5 views

Unit+7+Topic+Questions+-+ArrayList

The document contains a series of questions related to Java programming, specifically focusing on ArrayLists, methods, and sorting algorithms. Each question presents a code segment and asks for the expected output or the impact of certain changes to the code. The questions are designed to test understanding of Java concepts and problem-solving skills in the context of AP Computer Science A curriculum.

Uploaded by

Tanisha Bentick
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Unit+7+Topic+Questions+-+ArrayList

The document contains a series of questions related to Java programming, specifically focusing on ArrayLists, methods, and sorting algorithms. Each question presents a code segment and asks for the expected output or the impact of certain changes to the code. The questions are designed to test understanding of Java concepts and problem-solving skills in the context of AP Computer Science A curriculum.

Uploaded by

Tanisha Bentick
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

AP COMPUTER SCIENCE A Test Booklet

Unit 7 Topic Questions

1. Consider the following code segment.

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


animals.add("fox");
animals.add(0, "squirrel");
animals.add("deer");
animals.set(2, "groundhog");
animals.add(1, "mouse");
System.out.println(animals.get(2) + " and " + animals.get(3));

What is printed as a result of executing the code segment?


(A) mouse and fox
(B) fox and groundhog
(C) groundhog and deer
(D) fox and deer
(E) squirrel and groundhog

2. Consider the following code segment.

ArrayList<Integer> oldList = new ArrayList();


oldList.add(100);
oldList.add(200);
oldList.add(300);
oldList.add(400);
ArrayList<Integer> newList = new ArrayList();
newList.add(oldList.remove(1));
newList.add(oldList.get(2));
System.out.println(newList);

What, if anything, is printed as a result of executing the code segment?


(A) [100, 300, 400]
(B) [200, 300]
(C) [200, 400]
(D) Nothing is printed because the code segment does not compile.
(E) Nothing is printed because an IndexOutOfBoundsException will occur.

AP Computer Science A Page 1 of 15


Test Booklet

Unit 7 Topic Questions

3. Consider the following code segment.

ArrayList<Double> conditionRating = new ArrayList<Double>();


conditionRating.add(9.84);
conditionRating.add(8.93);
conditionRating.add(7.65);
conditionRating.add(6.24);
conditionRating.remove(2);
conditionRating.set(2, 7.63);
System.out.println(conditionRating);

What is printed when this code segment is executed?


(A) [9.84, 7.63, 6.24]
(B) [9.84, 7.63, 7.65, 6.24]
(C) [9.84, 8.93, 7.63]
(D) [9.84, 8.93, 7.63, 6.24]
(E) [9.84, 8.93, 7.65, 7.63]

4. Consider the following statement, which is intended to create an ArrayList named theater_club to store
elements of type Student. Assume that the Student class has been properly defined and includes a no-
parameter constructor.

ArrayList<Student> theater_club = new /* missing code */;

Which choice can replace /* missing code */ so that the statement compiles without error?
(A) Student()
(B) Student ArrayList()
(C) ArrayList(Student)
(D) ArrayList<Student>()
(E) ArrayList<theater_club>()

Page 2 of 15 AP Computer Science A


Test Booklet

Unit 7 Topic Questions

5. Consider the following method countNegatives, which searches an ArrayList of Integer objects
and returns the number of elements in the list that are less than 0.

public static int countNegatives(ArrayList<Integer> arr)


{
int count = 0;
for (int j = 0; j < arr.size(); j++) // Line 4
{
if (arr.get(j) < 0)
{
count++;
}
}
return count;
}

Which of the following best explains the impact to the countNegatives method when, in line 4, j <
arr.size() is replaced with j <= arr.size() - 1 ?
(A) It has no impact on the behavior of the method.
(B) It causes the method to ignore the last element in arr.
(C) It causes the method to throw an IndexOutOfBounds exception.
(D) It reduces the size of arr by 1 and the last element will be removed.
(E) It changes the number of times the loop executes, but all indexes in arr will still be accessed.

6. Consider the following method findValue, which takes an ArrayList of String elements and a
String value as parameters and returns true if the String value is found in the list and false
otherwise.

public static boolean findValue(ArrayList<String> arr, String key)


{
for (int j = 0; j < arr.size(); j++) // Line 3
{
if (arr.get(j).equals(key))
{
return true;
}
}
return false;
}

Which of the following best explains the impact to the findValue method when, in line 3, int j = 0 is
replaced by int j = 1 ?

AP Computer Science A Page 3 of 15


Test Booklet

Unit 7 Topic Questions

(A) It has no impact on the behavior of the method.


(B) It will cause the method to return a different result when the key value is not in the list.
It will cause the method to return a different result when the key value is found only at the first index in
(C)
the list.
It will cause the method to return a different result when the key value is found only at the last index in the
(D)
list.
(E) It will cause the method to throw an array index out of bounds exception.

7. Consider the following method, inCommon, which takes two Integer ArrayList parameters. The method
returns true if the same integer value appears in both lists at least one time, and false otherwise.

public static boolean inCommon(ArrayList<Integer> a, ArrayList<Integer> b)


{
for (int i = 0; i < a.size(); i++)
{
for (int j = 0; j < b.size(); j++) // Line 5
{
if (a.get(i).equals(b.get(j)))
{
return true;
}
}
}
return false;
}

Which of the following best explains the impact to the inCommon method when line 5 is replaced by for
(int j = b.size() - 1; j > 0; j--) ?
(A) The change has no impact on the behavior of the method.
(B) After the change, the method will never check the first element in list b.
(C) After the change, the method will never check the last element in list b.
(D) After the change, the method will never check the first and the last elements in list b.
(E) The change will cause the method to throw an IndexOutOfBounds exception.

Page 4 of 15 AP Computer Science A


Test Booklet

Unit 7 Topic Questions

8. In the following code segment, assume that the ArrayList wordList has been initialized to contain the
String values ["apple", "banana", "coconut", "lemon", "orange", "pear"].

int count = 0;
for (String word : wordList)
{
if (word.indexOf("a") >= 0)
{
count++;
}
}
System.out.println(count);

What is printed as a result of executing the code segment?


(A) 1
(B) 2
(C) 3
(D) 4
(E) 5

9. Consider the following method, remDups, which is intended to remove duplicate consecutive elements from
nums, an ArrayList of integers. For example, if nums contains {1, 2, 2, 3, 4, 3, 5, 5, 6},
then after executing remDups(nums), nums should contain {1, 2, 3, 4, 3, 5, 6}.

public static void remDups(ArrayList<Integer> nums)


{
for (int j = 0; j < nums.size() - 1; j++)
{
if (nums.get(j).equals(nums.get(j + 1)))
{
nums.remove(j);
j++;
}
}
}

The code does not always work as intended. Which of the following lists can be passed to remDups to show that
the method does NOT work as intended?
(A) {1, 1, 2, 3, 3, 4, 5}
(B) {1, 2, 2, 3, 3, 4, 5}
(C) {1, 2, 2, 3, 4, 4, 5}
(D) {1, 2, 2, 3, 4, 5, 5}
(E) {1, 2, 3, 3, 4, 5, 5}

AP Computer Science A Page 5 of 15


Test Booklet

Unit 7 Topic Questions

10. The removeElement method is intended to remove all instances of target from the ArrayList object
data passed as a parameter. The method does not work as intended for all inputs.

public void removeElement(ArrayList<Integer> data, int target)


{
for (int j = 0; j < data.size(); j++)
{
if (data.get(j).equals(target))
{
data.remove(j);
}
}
}

Assume that the ArrayList object scores and the int variable low_score have been properly
declared and initialized. In which of the following cases will the method call removeElement(scores,
low_score) fail to produce the intended result?
(A) When scores is [0, 2, 0, 2, 0, 6] and low_score is 0
(B) When scores is [2, 4, 0, 5, 7, 0] and low_score is 0
(C) When scores is [3, 4, 5, 7, 7, 2] and low_score is 1
(D) When scores is [8, 8, 4, 3, 3, 6] and low_score is 3
(E) When scores is [9, 9, 5, 9, 7, 7] and low_score is 5

11. In the following code segment, assume that the ArrayList numList has been properly declared and
initialized to contain the Integer values [1, 2, 2, 3]. The code segment is intended to insert the
Integer value val in numList so that numList will remain in ascending order. The code segment does
not work as intended in all cases.

int index = 0;
while (val > numList.get(index))
{
index++;
}
numList.add(index, val);

For which of the following values of val will the code segment not work as intended?
(A) 0
(B) 1
(C) 2
(D) 3
(E) 4

Page 6 of 15 AP Computer Science A


Test Booklet

Unit 7 Topic Questions

12. Consider the following correct implementation of the selection sort algorithm.

public static void selectionSort(int[] elements)


{
for (int j = 0; j < elements.length - 1; j++)
{
int minIndex = j;
for (int k = j + 1; k < elements.length; k++)
{
if (elements[k] < elements[minIndex])
{
minIndex = k;
}
}
if (j != minIndex)
{
int temp = elements[j];
elements[j] = elements[minIndex];
elements[minIndex] = temp; // Line 19
}
}
}

The following declaration and method call appear in a method in the same class as selectionSort.

int[] arr = {9, 8, 7, 6, 5};


selectionSort(arr);

How many times is the statement elements[minIndex] = temp; in line 19 of the method executed as a
result of the call to selectionSort ?
(A) 1
(B) 2
(C) 3
(D) 4
(E) 5

13. Consider the following statement, which is intended to create an ArrayList named values that can be used
to store Integer elements.

/* missing code */ = new ArrayList<>();

Which of the following can be used to replace /* missing code */ so that the statement compiles without error?

I. ArrayList values
II. ArrayList<int> values
III. ArrayList<Integer> values

AP Computer Science A Page 7 of 15


Test Booklet

Unit 7 Topic Questions

(A) I only
(B) II only
(C) III only
(D) I and III only
(E) II and III only

14. Consider the following statement, which is intended to create an ArrayList named years that can be used to
store elements both of type Integer and of type String.

/* missing code */ = new ArrayList();

Which of the following can be used to replace /* missing code */ so that the statement compiles without error?
(A) ArrayList years
(B) ArrayList years()
(C) ArrayList years[]
(D) ArrayList<Integer> years
(E) ArrayList<String> years

15. Consider the following correct implementation of the insertion sort algorithm.

public static void insertionSort(int[] elements)


{
for (int j = 1; j < elements.length; j++)
{
int temp = elements[j];
int possibleIndex = j;

{
elements[possibleIndex] = elements[possibleIndex - 1];
possibleIndex--; // Line 10
}
elements[possibleIndex] = temp;
}
}

The following declaration and method call appear in a method in the same class as insertionSort.

int[] arr = {4, 12, 4, 7, 19, 6};


insertionSort(arr);

How many times is the statement possibleIndex--; in line 10 of the method executed as a result of the call
to insertionSort ?

Page 8 of 15 AP Computer Science A


Test Booklet

Unit 7 Topic Questions

(A) 2
(B) 3
(C) 4
(D) 5
(E) 6

16. Consider the following correct implementation of the selection sort algorithm.

public static void selectionSort(int[] elements)


{
for (int j = 0; j < elements.length - 1; j++)
{
int minIndex = j;
for (int k = j + 1; k < elements.length; k++)
{
if (elements[k] < elements[minIndex])
{
minIndex = k; // Line 11
}
}
if (j != minIndex)
{
int temp = elements[j];
elements[j] = elements[minIndex];
elements[minIndex] = temp;
}
}
}

The following declaration and method call appear in the same class as selectionSort.

int[] vals = {5, 10, 2, 1, 12};


selectionSort(vals);

How many times is the statement minIndex = k; in line 11 of the method executed as a result of the call to
selectionSort ?
(A) 0
(B) 1
(C) 2
(D) 3
(E) 4

AP Computer Science A Page 9 of 15


Test Booklet

Unit 7 Topic Questions

17. In the following code segment, assume that the ArrayList data has been initialized to contain the
Integer values [4, 3, 4, 5, 3, 4].

int j = 0;
while (j < data.size() - 1)
{
if (data.get(j) > data.get(j + 1))
{
System.out.print(data.get(j + 1) + " ");
}
j++;
}

What, if anything, is printed as a result of executing the code segment?


(A) 3 3
(B) 4 5
(C) 4 5 4
(D) Nothing is printed because the code segment does not compile.
(E) Nothing is printed because an IndexOutOfBoundsException occurs.

18. In the code segment below, assume that the ArrayList object numbers has been properly declared and
initialized to contain [0, 2, 4, 5].

for (int k = numbers.size() - 1; k >= 0; k--)


{
if (numbers.get(k) > k)
{
System.out.print(k + " ");
}
}

What, if anything, is printed as a result of executing the code segment?


(A) 1 2 3
(B) 2 4 5
(C) 3 2 1
(D) 5 4 2
(E) Nothing will be printed because an IndexOutOfBoundsException will occur.

Page 10 of 15 AP Computer Science A


Test Booklet

Unit 7 Topic Questions

19. SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.

Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are
called only when their preconditions are satisfied.
In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined
in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will
not receive full credit.

This question involves the scheduling of car repairs. The classes used in the question are used to record information
about car repairs. The methods shown and the methods to be written involve the mechanic performing a repair and the
bay in which the repair takes place. A bay is an area of a repair shop in which a car is parked while a mechanic
performs a repair. Mechanics and bays are identified by sequential integer identification numbers that start with 0.

An individual car repair is represented by the following CarRepair class.

public class CarRepair


{
private int mechanicNum;
private int bayNum;

public CarRepair(int m, int b)


{
mechanicNum = m;
bayNum = b;
}

public int getMechanicNum()


{ return mechanicNum; }

public int getBayNum()


{ return bayNum; }

// There may be other instance variables, constructors, and methods


not shown.
}

The following RepairSchedule class represents the use of bays by mechanics repairing cars. You will write two
methods of the RepairSchedule class.

public class RepairSchedule


{
/** Each element represents a repair by an individual mechanic in a
bay. */
private ArrayList<CarRepair> schedule;

AP Computer Science A Page 11 of 15


Test Booklet

Unit 7 Topic Questions

/** Number of mechanics available in this schedule. */


private int numberOfMechanics;

/** Constructs a RepairSchedule object.


* Precondition: n >= 0
*/
public RepairSchedule(int n)
{
schedule = new ArrayList<CarRepair>();
numberOfMechanics = n;
}

/** Attempts to schedule a repair by a given mechanic in a given bay


as described in part (a).
* Precondition: 0 <= m < numberOfMechanics and b >= 0
*/
public boolean addRepair(int m, int b)
{
/* to be implemented in part (a) */
}

/** Returns an ArrayList containing the mechanic identifiers of all


available mechanics,
* as described in part (b).
*/
public ArrayList<Integer> availableMechanics()
{
/* to be implemented in part (b) */
}

/** Removes an element from schedule when a repair is complete. */


public void carOut(int b)
{
/* implementation not shown */
}
}

(a) Write the addRepair method. The method attempts to schedule a repair by the mechanic with identifier m in the
bay with identifier b. The repair can be scheduled if mechanic m and bay b are both available. A mechanic is available
if the given mechanic number does not appear in an element of schedule and a bay is available if the given bay
number does not appear in an element of schedule.

If the mechanic and bay are both available, the addRepair method adds the repair to schedule and returns true.
If either the mechanic or the bay are not available, the addRepair method returns false.

The following sequence of statements provides examples of the behavior of the addRepair method.

Page 12 of 15 AP Computer Science A


Test Booklet

Unit 7 Topic Questions

The statement RepairSchedule r = new RepairSchedule(6); constructs a new


RepairSchedule object r. No repairs have been scheduled. Mechanics are numbered 0 through 5.
The call r.addRepair(3, 4) returns true because neither mechanic 3 nor bay 4 are present in schedule.
The contents of schedule after the call are as follows.

The call r.addRepair(0, 1) returns true because neither mechanic 0 nor bay 1 are present in schedule.
The contents of schedule after the call are as follows.

The call r.addRepair(0, 2) returns false because mechanic 0 is present in schedule. The contents of
schedule after the call are as follows.

The call r.addRepair(2, 4) returns false because bay 4 is present in schedule. The contents of
schedule after the call are as follows.

The call r.carOut(4) removes the repair in bay 4 from schedule. The carOut method is shown here to
illustrate that bays and mechanics become available when car repairs are complete. You do not need to write or
call this method. The contents of schedule after the call are as follows.

AP Computer Science A Page 13 of 15


Test Booklet

Unit 7 Topic Questions

The call r.addRepair(1, 4) returns true because neither mechanic 1 nor bay 4 are present in schedule.
The contents of schedule after the call are as follows.

Complete the addRepair method.

/** Attempts to schedule a repair by a given mechanic in a given bay


as described in part (a).
* Precondition: 0 <= m < numberOfMechanics and b >= 0
*/
public boolean addRepair(int m, int b)

(b) Write the availableMechanics method, which returns an ArrayList containing the mechanic numbers of
all available mechanics. If there is no available mechanic, an empty list is returned. A mechanic is available if the
mechanic’s identifier does not appear in schedule. Suppose schedule has the following contents.

For these contents of schedule, availableMechanic should return an ArrayList containing the values 2, 3,
4, and 5 (in any order).

Complete the availableMechanics method. Assume that addRepair works as specified, regardless of what you
wrote in part (a).

/** Returns an ArrayList containing the mechanic identifiers of all


available mechanics,

Page 14 of 15 AP Computer Science A


Test Booklet

Unit 7 Topic Questions

* as described in part (b).


*/
public ArrayList<Integer> availableMechanics()

AP Computer Science A Page 15 of 15

You might also like