Study Guide ch 7 for comp sci
Consider the following code segment. ArrayList<String> arrList = new ArrayList<String>(); arrList.add("A"); arrList.add("B"); arrList.add("C"); arrList.add("D"); for (int i = 0; i < arrList.size(); i++) { System.out.print(arrList.remove(i)); } What, if anything, is printed as a result of executing the code segment?
AC
Consider the following correct implementation of the insertion sort algorithm. The insertionSort method correctly sorts the elements of ArrayList data into increasing order. public static void insertionSort(ArrayList<Integer> data) { for (int j = 1; j < data.size(); j++) { int v = data.get(j); int k = j; while (k > 0 && v < data.get(k - 1)) { data.set(k, data.get(k - 1)); /* Statement 1 */ k--; } data.set(k, v); /* Statement 2 */ /* End of outer loop */ } } Question Assume that insertionSort is called with an ArrayList parameter that has been initialized with the following Integer objects. [1, 2, 3, 4, 5, 6] How many times will the statements indicated by /* Statement 1 */ and /* Statement 2 */ execute?
Statement 1: 0 Statement 2: 5
Consider the following code segment. List<String> animals = new ArrayList<String>(); animals.add("dog"); animals.add("cat"); animals.add("snake"); animals.set(2, "lizard"); animals.add(1, "fish"); animals.remove(3); System.out.println(animals); What is printed as a result of executing the code segment?
[dog, fish, cat]
Consider the following code segment. ArrayList<String> words = new ArrayList<String>(); words.add("mat"); words.add("new"); words.add("open"); words.add("pet"); int i = 0; while (i < words.size()) { words.remove(i); i++; } System.out.println(words.toString()); What is printed when the code segment is executed?
[new, pet]
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?
fox and groundhog
The following questions refer to the code in the GridWorld case study. A copy of the code is provided below. Consider the design of a Grasshopper class that extends Bug. When asked to move, a Grasshopper moves to a randomly chosen empty adjacent location that is within the grid. If there is no empty adjacent location that is within the grid, the Grasshopper does not move, but turns 45 degrees to the right without changing its location. Appendix B — Testable API info.gridworld.grid.Location class (implements Comparable)
grd.get(loc).getDirection()
Consider the following class definition. public class Value { private int num; public int getNum() { return num; } // There may be instance variables, constructors, and methods not shown. } The following method appears in a class other than Value. It is intended to sum all the num instance variables of the Value objects in its ArrayList parameter. /** Precondition: valueList is not null */ public static int getTotal(ArrayList<Value> valueList) { int total = 0; /* missing code */ return total; } Which of the following code segments can replace /* missing code */ so the getTotal method works as intended?
i and ii for (int x = 0; x < valueList.size(); x++) { total += valueList.get(x).getNum(); } for (Value v: valueList) { total += v.getNum(); }
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? 1. ArrayList values 2. ArrayList<int> values 3. ArrayList<Integer> values
i and iii only ArrayList values ArrayList<Integer> values
The following incomplete method is intended to sort its array parameter arr in increasing order. // postcondition: arr is sorted in increasing order public static void sortArray(int[] arr) { int j, k; for (j = arr.length - 1; j > 0; j--) { int pos = j; for ( /* missing code */ ) { if (arr[k] > arr[pos]) { pos = k; } } swap(arr, j, pos); } } Assume that swap(arr, j, pos) exchanges the values of arr[j] and arr[pos]. Which of the following could be used to replace /* missing code */ so that executing the code segment sorts the values in array arr?
k = j - 1; k >= 0; k--
Consider the following method that is intended to modify its parameter nameList by replacing all occurrences of name with newValue. public void replace(ArrayList<String> nameList, String name, String newValue) { for (int j = 0; j < nameList.size(); j++) { if ( /* expression */ ) { nameList.set(j, newValue); } } } Which of the following can be used to replace /* expression */ so that replace will work as intended?
nameList.get(j).equals(name)
Consider the following instance variable and method. Method wordsWithCommas is intended to return a string containing all the words in listOfWords separated by commas and enclosed in braces.For example, if listOfWords contains ["one", "two", "three"], the string returned by the call wordsWithCommas () should be "{one, two, three}". Which of the following can be used to replace /* expression */ and /* condition */ so thatwordsWithCommas will work as intended?
/ * expression * / / / * condition * / listOfWords.size() / k != sizeOfList - 1
Consider the following method. public static void sort(String[] arr) { for (int pass = arr.length - 1; pass >= 1; pass--) { String large = arr[0]; int index = 0; for (int k = 0; k <= pass; k++) { if ((arr[k].compareTo(large)) > 0) { large = arr[k]; index = k; } } arr[index] = arr[pass]; arr[pass] = large; } } Assume arr is the following array. What is the intermediate value of arr after two iterations of the outer for loop in the call sort(arr)?
"Ann" "Mike" "Bill" "Lisa" "Mary" "Jose" "Shari" "Walt"
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?
ArrayList years
Consider the following code segment. ArrayList<String> numbers = new ArrayList<String>(); numbers.add("one"); numbers.add("two"); numbers.add(0, "three"); numbers.set(2, "four"); numbers.add("five"); numbers.remove(1); Which of the following represents the contents of numbers after the code segment has been executed?
["three", "four", "five"]
Consider the following declaration of the class NumSequence, which has a constructor that is intended to initialize the instance variable seq to an ArrayList of numberOfValues random floating-point values in the range [0.0, 1.0). public class NumSequence { private ArrayList<Double> seq; // precondition: numberOfValues > 0 // postcondition: seq has been initialized to an ArrayList of // length numberOfValues; each element of seq // contains a random Double in the range [0.0, 1.0) public NumSequence(int numberOfValues) { /* missing code */ } } Which of the following code segments could be used to replace /* missing code */ so that the constructor will work as intended?
ii and iii seq = new ArrayList<Double>(); for(int k = 0; k < numberOfValues; k++) seq.add(new Double(Math.random())); ArrayList<Double> temp = new ArrayList<Double>(); for (int k = 0; k < numberOfValues; k++) temp.add(new Double(Math.random())); seq = temp;
Consider the following method. /** Removes all occurrences of nameToRemove from nameList. * @param nameList a list of names * @param nameToRemove a name to be removed from nameList */ public void removeName(List<String> nameList, String nameToRemove) { /* missing implementation */ } Which of the following can be used to replace /* missing implementation */ so that removeName will work as intended?
iii only for (int k = nameList.size() - 1; k >= 0; k--) { if (nameList.get(k).equals(nameToRemove)) nameList.remove(k); }
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?
3 2 1
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?
3 3
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 ?
4
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; while (possibleIndex > 0 && temp < elements[possibleIndex - 1]) { elements[possibleIndex] = elements[possibleIndex - 1]; possibleIndex--; } elements[possibleIndex] = temp; // line 12 } } The following declaration and method call appear in a method in the same class as insertionSort. int[] nums = {8, 7, 5, 4, 2, 1}; insertionSort(nums); How many times is the statement elements[possibleIndex] = temp; in line 12 of the method executed as a result of the call to insertionSort ?
5
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; while (possibleIndex > 0 && temp < elements[possibleIndex - 1]) { 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 = {10, 8, 3, 4}; insertionSort(arr); How many times is the statement possibleIndex--; in line 10 of the method executed as a result of the call to insertionSort ?
5
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; while (possibleIndex > 0 && temp < elements[possibleIndex - 1]) { 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 ?
5
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--) ?
After the change, the method will never check the first element in list b.
Consider the following code segment. List<String> students = new ArrayList<String>(); students.add("Alex"); students.add("Bob"); students.add("Carl"); for(int k = 0; k < students.size(); k++) { System.out.print(students.set(k, "Alex") + " "); } System.out.println(); for(String str : students) { System.out.print(str + " "); } What is printed as a result of executing the code segment?
Alex Bob Carl Alex Alex Alex
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?
ArrayList<Student>()
Consider the method seqSearch, which implements a sequential search algorithm. public int seqSearch(int[] arr, int target) { for (int j = 0; j < arr.length; j++) { if (arr[j] == target) { return j; } } return -1; } Consider another method, seqSearch2, which modifies seqSearch to use an enhanced for loop. public int seqSearch2(int[] arr, int target) { for (int j : arr) { if (j == target) { return j; } } return -1; } Which of the following best describes the difference in the behavior of seqSearch2 relative to seqSearch as a result of the modification?
The modification in seqSearch2 will cause the value of target to be returned instead of the index of target in cases where target appears in arr.
Consider the following search method. public static int search(int[] arr, int target) { int result = -1; for (int j = 0; j < arr.length; j++) { if (arr[j] == target) { result = j; // Line 8 } } return result; } Which of the following describes the effect of replacing the statement in line 8 of the method with result = arr[j]; ?
The modified method will return target if target appears in arr and will return -1 otherwise.
Consider the method sequentialSearch, which takes an ArrayList of Integer elements and an int value as parameters and returns the index of the first appearance of the target value in the list or -1 if the target value does not appear in the list. public static int sequentialSearch(ArrayList<Integer> elements, int target) { for (int j = 0; j < elements.size(); j++) // Line 3 { if (elements.get(j) == target) { return j; } } return -1; } Which of the following explains how replacing Line 3 with for (int j = (elements.size() - 1); j >= 0; j--) will affect the behavior of sequentialSearch?
The modified method will return the index of the last appearance of the target value in the list, or -1 if the target value does not appear in the list.
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?
When scores is [8, 8, 4, 3, 3, 6] and low_score is 3
Consider the following method. public static void mystery(List<Integer> nums) { for (int k = 0; k < nums.size(); k++) { if (nums.get(k).intValue() == 0) { nums.remove(k); } } } Assume that a List<Integer> values initially contains the following Integer values. [0, 0, 4, 2, 5, 0, 3, 0] What will values contain as a result of executing mystery(values) ?
[0, 4, 2, 5, 3]
Consider the following code segment. ArrayList<Integer> nums = new ArrayList<Integer>(); nums.add(new Integer(37)); nums.add(new Integer(3)); nums.add(new Integer(0)); nums.add(1, new Integer(2)); nums.set(0, new Integer(1)); nums.remove(2); System.out.println(nums); What is printed as a result of executing the code segment?
[1, 2, 0]
Consider the following correct implementation of the insertion sort algorithm. The insertionSort method correctly sorts the elements of ArrayList data into increasing order. public static void insertionSort(ArrayList<Integer> data) { for (int j = 1; j < data.size(); j++) { int v = data.get(j); int k = j; while (k > 0 && v < data.get(k - 1)) { data.set(k, data.get(k - 1)); /* Statement 1 */ k--; } data.set(k, v); /* Statement 2 */ /* End of outer loop */ } } Question Assume that insertionSort has been called with an ArrayList parameter that has been initialized with the following Integer objects. [5, 2, 4, 1, 3, 6] What will the contents of data be after three passes of the outside loop (i.e., when j == 3 at the point indicated by /* End of outer loop */) ?
[1, 2, 4, 5, 3, 6]
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?
[200, 400]
Consider the following code segment. ArrayList<Integer> nums = new ArrayList<Integer>(); nums.add(3); nums.add(2); nums.add(1); nums.add(0); nums.add(0, 4); nums.set(3, 2); nums.remove(3); nums.add(2, 0); Which of the following represents the contents of nums after the code segment has been executed?
[4, 3, 0, 2, 0]
Consider the following method public ArrayList<Integer> mystery(int n) { ArrayList<Integer> seq = new ArrayList<Integer>(); for (int k = 1; k <= n; k++) seq.add(new Integer(k * k + 3)); return seq; } Which of the following is printed as a result of executing the following statement?
[4, 7, 12, 19, 28, 39]
Consider the following data field and method. private ArrayList list; public void mystery(int n) { for (int k = 0; k < n; k++) { Object obj = list.remove(0); list.add(obj); } } Assume that list has been initialized with the following Integer objects. [12, 9, 7, 8, 4, 3, 6, 11, 1] Which of the following represents the list as a result of a call to mystery(3)?
[8, 4, 3, 6, 11, 1, 12, 9, 7]
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?
[9.84, 8.93, 7.63]
Consider the following code segment. ArrayList<String> syllables = new ArrayList<String>(); syllables.add("LA"); syllables.add(0, "DI"); syllables.set(1, "TU"); syllables.add("DA"); syllables.add(2, syllables.get(0)); syllables.remove(1); System.out.println(syllables.toString()); What is printed as a result of executing the code segment?
[DI, DI, DA]
Consider the following code segment. ArrayList<String> items = new ArrayList<String>(); items.add("A"); items.add("B"); items.add("C"); items.add(0, "D"); items.remove(3); items.add(0, "E"); System.out.println(items); What is printed as a result of executing the code segment?
[E, D, A, B]
Consider the following code segment. ArrayList<String> colors = new ArrayList<String>(); colors.add("Red"); colors.add("Orange"); colors.set(1, "Yellow"); colors.add(1, "Green"); colors.set(colors.size() - 1, "Blue"); colors.remove(0); System.out.println(colors); What is printed as a result of executing the code segment?
[Green, Blue]
Consider the following statement, which is intended to create an ArrayList named a to store only elements of type Thing. Assume that the Thing class has been properly defined and includes a no-parameter constructor. ArrayList<Thing> a = /* missing code */; Which of the following can be used to replace /* missing code */ so that the statement works as intended?
new ArrayList<Thing>()
In the code segment below, myList is an ArrayList of integers. The code segment is intended to remove all elements with the value 0 from myList. int j = 0; while (j < myList.size()) { if (myList.get(j) == 0) { myList.remove(j); } j++; } The code segment does not always work as intended. For which of the following lists does the code segment NOT produce the correct result?
{1, 0, 0, 2}
Consider the following statement, which is intended to create an ArrayList named arrList to store elements only of type String. /* missing code */ = new ArrayList<String>(); Which of the following can be used to replace /* missing code */ so that the statement works as intended? Responses
ArrayList<String> arrList
Consider the following code segment from an insertion sort program. for(int j = 1; j < arr.length; j++) { int insertItem = arr[j]; int k = j - 1; while (k >= 0 && insertItem < arr[k]) { arr[k + 1] = arr[k]; k--; } arr[k + 1] = insertItem; } Assume that array arr has been defined and initialized with the values {5, 4, 3, 2, 1}. What are the values in array arr after two passes of the for loop (i.e., when j = 2 at the point indicated by / * end of for loop * / ) ?
{3, 4, 5, 2, 1}
Assume that myList is an ArrayList that has been correctly constructed and populated with objects. Which of the following expressions produces a valid random index for myList?
(int) ( Math.random () * myList.size () )
Which of the following is a reason to use an ArrayList instead of an array?
An ArrayList resizes itself as necessary when items are added, but an array does not.
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 ?
It has no impact on the behavior of the method.
Consider the following code segment. ArrayList<Integer> vals = new ArrayList<Integer>(); vals.add(vals.size(), vals.size()); vals.add(vals.size() - 1, vals.size() + 1); vals.add(vals.size() - 2, vals.size() + 2); System.out.println(vals.toString()); What is printed as a result of executing the code segment?
[4, 2, 0]
Consider the following instance variable and method. 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?
["bear", "zebra", "bass", "cat", "koala", "baboon"]
Consider the following code segment. ArrayList<Integer> numList = new ArrayList<Integer>(); numList.add(3); numList.add(2); numList.add(1); numList.add(1, 0); numList.set(0, 2); System.out.print(numList); What is printed by the code segment?
[2, 0, 2, 1]
Consider the following method, which is intended to return a list containing the elements of the parameter myList with all even elements removed. public static ArrayList<Integer> removeEvens(ArrayList<Integer> myList) { for (int i = 0; i < myList.size(); i++) { if (myList.get(i) % 2 == 0) { myList.remove(i); } } return myList; } Which of the following best explains why the code segment does not work as intended?
The code segment skips some elements of myList because the indexes of all subsequent elements change by one when a list element is removed.
The following method is intended to remove all elements of an ArrayList of integers that are divisible by key and add the removed elements to a new ArrayList, which the method returns. public static ArrayList<Integer> match(ArrayList<Integer> numList, int key) { ArrayList<Integer> returnList = new ArrayList<Integer>(); int i = 0; while (i < numList.size()) { int num = numList.get(i); if (num % key == 0) { numList.remove(i); returnList.add(num); } i++; } return returnList; } As an example, if the method is called with an ArrayList containing the values [5, 2, 10, 20, 16] and the parameter key has the value 5, then numList should contain [2, 16] at the end of the method and an ArrayList containing [5, 10, 20] should be returned. Which of the following best explains why the method does not always work as intended?
The method skips some elements of numList during the traversal.
Consider the following code segment. ArrayList<Integer> myList = new ArrayList<Integer>(); for (int i = 0; i < 4; i++) { myList.add(i + 1); } for (int i = 0; i < 4; i++) { if (i % 2 == 0) { System.out.print(myList.get(i) + " "); } } What output is produced as a result of executing the code segment?
1 3
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 ?
2
The following question refer to the following information. Consider the following data field and method. The method removeDups is intended to remove all adjacent duplicate numbers from myData, but does not work as intended. private ArrayList myData; public void removeDups () { int k = 1; while (k < myData.size()) { if (myData.get(k).equals(myData.get(k - 1))) { myData.remove(k); } k++; } } For example, if myData has the values 3 3 4 4 4 8 7 7 7, after calling removeDups, myData should have the values 3 4 8 7. Assume that myData has the following values. 2 7 5 5 5 5 6 6 3 3 3 Which of the following representsmyDataafter the incorrectremoveDupsis executed?
2 7 5 5 6 3 3
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 = {30, 40, 10, 50, 20}; 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 ?
3
In the code segment below, numList is an ArrayList of integers that is sorted in descending order. The code segment is intended to insert the integer value val into numList so that numList is still sorted in descending order. int j = 0; while (val != numList.get(j)) { j++; } numList.add(j, val); The code segment does not always work as intended. Assuming that numList has been initialized to {3, 2, 1, 0}, for which value of val does the code segment NOT produce the expected result?
4
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?
4
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?
4
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 ?
It will cause the method to return a different result when the key value is found only at the first index in the list.
Consider the static method selectSort shown below. Method selectSort is intended to sort an array into increasing order; however, it does not always work as intended. // precondition: numbers.length > 0 // postcondition: numbers is sorted in increasing order public static void selectSort(int[] numbers) { int temp; Line 1: for (int j = 0; j < numbers.length - 1; j++) { Line 2: int pos = 0; Line 3: for (int k = j + 1; k < numbers.length; k++) { Line 4: if (numbers[k] < numbers[pos]) { Line 5: pos = k; } } temp = numbers[j]; numbers[j] = numbers[pos]; numbers[pos] = temp; } } Which of the following changes should be made so that selectSort will work as intended?
Line 2 should be changed to int pos = j;
The following question refer to the following information. Consider the following data field and method. The method removeDups is intended to remove all adjacent duplicate numbers from myData, but does not work as intended. private ArrayList myData; public void removeDups () { int k = 1; while (k < myData.size()) { if (myData.get(k).equals(myData.get(k - 1))) { myData.remove(k); } k++; } } For example, if myData has the values 3 3 4 4 4 8 7 7 7, after calling removeDups, myData should have the values 3 4 8 7. Which of the following best describes how to fix the error so that removeDups works as intended?
There should be an else before the statement k++;
Consider the following method definition. The method isReversed is intended to return true if firstList and secondList contain the same elements but in reverse order, and to return false otherwise. /** Precondition: firstList.size() == secondList.size() */ public static boolean isReversed(ArrayList<Integer> firstList, ArrayList<Integer> secondList) { for (int j = 0; j < firstList.size() / 2; j++) { if (firstList.get(j) != secondList.get(secondList.size() - 1 - j)) { return false; } } return true; } The method does not always work as intended. For which of the following inputs does the method NOT return the correct value?
When firstList is {1, 3, 5, 7} and secondList is {5, 5, 3, 1}
Directions: Select the choice that best fits each statement. The following question(s) refer to the following information. Consider the following sort method. This method correctly sorts the elements of array data into increasing order. public static void sort(int [] data) { for (int j = 0; j < data.length - 1; j++) { int m = j; for (int k = j + 1; k < data.length; k++) { if (data[k] < data[m]) { m = k; } } int temp = data[m]; data[m] = data[j]; data[j] = temp; } } Assume that sort is called with the array {1, 2, 3, 4, 5, 6}. How many times will the expression indicated by /* Compare values */ and the statement indicated by /* Assign to temp */ execute?
compare values / assign to temp 15 / 5
Consider the following two data structures for storing several million words. I. An array of words, not in any particular order II. An array of words, sorted in alphabetical order Which of the following statements most accurately describes the time needed for operations on these data structures?
finding a given word is faster in ii than in i
Consider the following statement, which is intended to create an ArrayList named numbers that can be used to store Integer values. ArrayList<Integer> numbers = /* missing code */; Which of the following can be used to replace /* missing code */ so that the statement works as intended? i new Integer() ii new ArrayList<Integer> iii new ArrayList<Integer>()
i and iii only new integer() new ArrayList<Integer>()
The following sort method correctly sorts the integers in elements into ascending order Which of the following changes to the sort method would correctly sort the integers in elements into descending order?
i and iii only replace line 9 with replace line 3 and 7 with
Consider the following class declaration. public class StudentInfo { private String major; private int age; public String getMajor() public int getAge() } The following instance variable and method appear in another class. private List<StudentInfo> students; public double averageAgeInMajor(String theMajor) { double sum = 0.0; int count = 0; for (StudentInfo k : students) { } if (count > 0) { return sum / count; } else { return - 1.0; } } Which of the following could be used to replace /* missing code */ so that averageAgeInMajor will compile without error? Responses
if (theMajor.equals(k.getMajor())) { sum += k.getAge(); count++; }
Consider the following interface and class declarations. public interface Vehicle { double getMileage(); } public class Fleet { private ArrayList<Vehicle> myVehicles; public double getTotalMileage() { double sum = 0.0; for (Vehicle v : myVehicles) { sum += /* expression */; } return sum; } } Which of the following can be used to replace /* expression */ so that getTotalMileage returns the total of the miles traveled for all vehicles in the fleet?
v.getMileage()
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?
{1, 2, 2, 3, 3, 4, 5}
Directions: Select the choice that best fits each statement. The following question(s) refer to the following information. Consider the following sort method. This method correctly sorts the elements of array data into increasing order. public static void sort(int[] data) { for (int j = 0; j < data.length - 1; j++) { int m = j; for (int k = j + 1; k < data.length; k++) { if (data[k] < data[m]) { m = k; } } int temp = data[m]; data[m] = data [j]; data[j] = temp; } } Question Assume that sort is called with the array {6, 3, 2, 5, 4, 1}. What will the value of data be after three passes of the outer loop (i.e., when j = 2 at the point indicated by / * End of outer loop * /) ?
{1, 2, 3, 5, 4, 6}