Test 1

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Fill in the code to complete the following method for checking whether a string is a palindrome. public static boolean isPalindrome(String s) { i f (s.length() <= 1) // Base case return true; else if _____________________________ return false; else return isPalindrome(s.substring(1, s.length() - 1)); }

(s.charAt(0) != s.charAt(s.length() - 1)) // Base case

Which of the following statements are true?

-A PriorityQueue orders its elements according to their natural ordering using the Comparable interface if no Comparator is specified. -A PriorityQueue orders its elements according to the Comparator if a Comparator is specified in the constructor.

Which of the following statements are true?

-An ArrayList can grow automatically. -You can reduce the capacity of an ArrayList by invoking the trimToSize() method on the list.

Which of the following statements is correct?

-Comparable<String> c = new String("abc"); -Comparable<String> c = "abc";

Which of the following statements is correct about generics?

-Generics can help detect type errors at compile time, thus make programs more robust. -Generics can make programs easy to read. -Generics can avoid cumbersome castings.

What is the return value for xMethod(4) after calling the following method? static int xMethod(int n) { if (n == 1) return 1; else return n + xMethod(n - 1); }

10

Fill in the code in Comparable______ c = new Date();

<Date>

To create a generic type bounded by Number, use

<E extends Number>

Which of the following can be used to replace YYYYYYYY in the following code? public class WildCardDemo3 { public static void main(String[] args) { GenericStack<String> stack1 = new GenericStack<>(); GenericStack<Object> stack2 = new GenericStack<>(); stack2.push("Java"); stack2.push(2); stack1.push("Sun"); add(stack1, stack2); WildCardDemo2.print(stack2); } public static <T> void add(GenericStack<T> stack1, GenericStack<YYYYYYYY> stack2) { while (!stack1.isEmpty()) stack2.push(stack1.pop()); } }

? super T

What is the printout of the following code? List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); for (int i = 0; i < list.size(); i++) System.out.print(list.remove(i));

AC

Which of the following declarations use raw type?

ArrayList list = new ArrayList();

To create a list to store integers, use

ArrayList<Integer> list = new ArrayList<>();

Which of the following is correct to create a list from an array?

Arrays.asList<String>(new String[]{"red", "green", "blue"})

Suppose list1 is an ArrayList and list2 is a LinkedList. Both contains 1 million double values. Analyze the following code A: for (int i = 0; i < list1.size(); i++) sum += list1.get(i); B: for (int i = 0; i < list2.size(); i++) sum += list2.get(i);

Code fragment A runs faster than code fragment B.

Suppose list is a LinkedList that contains 1 million int values. Analyze the following code: A: for (int i = 0; i < list.size(); i++) sum += list.get(i); B: for (int i: list) sum += i;

Code fragment B runs faster than code fragment A

To remove all the elements in the list in the following code, replace the underlined blank space with __________. import java.util.*; public class Test { public static void main(String[] args) { ______________<Integer> list = new ArrayList<>(); list.add(0); list.add(1); list.add(2); for (int i = 0; i < 3; i++) { list.remove(i); } System.out.println(list); } }

Collection

To find a maximum object in an array of strings (e.g., String[] names = {"red", "green", "blue"}), use

Collections.max(Arrays.asList(names))

Which of the following statements are true?

Collections.nCopies(int, Object) returns a new list that consists of n copies of the object.

The iterator() method is defined in the __________ interface.

Iterable

You can use a for-each loop to traverse all elements in a container object that implements _____.

Iterable

The iterator() method returns an instance of the __________ interface.

Iterator

Which data type should you use if you want to store duplicate elements and be able to insert or delete elements at the beginning of the list?

LinkedList

ArrayList<String> and ArrayList<Integer> are two types. Does the JVM load two classes ArrayList<String> and ArrayList<Integer>?

No

If E is a generic type for a class, can E be referenced from a static method?

No

Is ArrayList<Integer> a subclass of ArrayList<Object>?

No

Which of the data types below does not allow duplicates?

Set

Analyze the following recursive method. public static long factorial(int n) { return n * factorial(n - 1); }

The method runs infinitely and causes a StackOverflowError.

Analyze the following code: import java.util.*; public class Test { public static void main(String[] args) { PriorityQueue<Integer> queue = new PriorityQueue<Integer>( Arrays.asList(60, 10, 50, 30, 40, 20)); while (!queue.isEmpty()) System.out.print(queue.poll() + " "); } }

The program displays 10 20 30 40 50 60

Analyze the following code: public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4, 5}; xMethod(x, 5); } public static void xMethod(int[] x, int length) { System.out.print(" " + x[length - 1]); xMethod(x, length - 1); } }

The program displays 5 4 3 2 1 and then raises an ArrayIndexOutOfBoundsException.

Analyze the following two programs: A: public class Test { public static void main(String[] args) { xMethod(5); } public static void xMethod(int length) { if (length > 1) { System.out.print((length - 1) + " "); xMethod(length - 1); } } } B: public class Test { public static void main(String[] args) { xMethod(5); } public static void xMethod(int length) { while (length > 1) { System.out.print((length - 1) + " "); xMethod(length - 1); } } }

The two programs produce the same output 1 2 3 4 5

Analyze the following code: import java.util.*; public class Test { public static void main(String[] args) { PriorityQueue<Integer> queue = new PriorityQueue<Integer>( Arrays.asList(60, 10, 50, 30, 40, 20)); for (int i: queue) System.out.print(i + " "); } }

There is no guarantee that the program displays 10 20 30 40 50 60

Which of the data types below could be used to store elements in their natural order based on the compareTo method?

TreeSet

The methods for modifying element in the ___________ class are synchronized.

Vector

Is ArrayList<Integer> a subclass of ArrayList<?>?

Yes

What is the output for the following code? import java.util.*; public class Test { public static void main(String[] args) { Set<A> set = new HashSet<>(); set.add(new A()); set.add(new A()); set.add(new A()); set.add(new A()); System.out.println(set); } } class A { int r = 1; public String toString() { return r + ""; } public boolean equals(Object o) { return this.r == ((A)o).r; } }

[1, 1, 1, 1]

Suppose list list1 is [1, 2, 5] and list list2 is [2, 3, 6]. After list1.addAll(list2), list1 is __________.

[1, 2, 2, 3, 5, 6]

Suppose set s1 is [1, 2, 5] and set s2 is [2, 3, 6]. After s1.addAll(s2), s1 is __________.

[1, 2, 3, 5, 6]

What is list after the following code is executed? ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); list.remove(2); System.out.println(list);

[1, 2, 4, 5]

What is the output of the following code? import java.util.*; public class Test { public static void main(String[] args) { Set<String> set1 = new HashSet<>(); set1.add("Atlanta"); set1.add("Macon"); set1.add("Savanna");

a

For an instance of Collection, you can obtain its iterator using ________________.

c.iterator()

The __________ method in the Queue interface retrieves, but does not remove, the head of this queue, throwing an exception if this queue is empty.

element()

Analyze the following functions; public class Test1 { public static void main(String[] args) { System.out.println(f1(3)); System.out.println(f2(3, 0)); } public static int f1(int n) { if (n == 0) return 0; else { return n + f1(n - 1); } } public static int f2(int n, int result) { if (n == 0) return result; else return f2(n - 1, n + result); } }

f2 is tail recursion, but f1 is not

Fill in the code to complete the following method for computing a Fibonacci number. public static long fib(long index) { if (index == 0) // Base case return 0; else if (index == 1) // Base case return 1; else // Reduction and recursive calls return __________________; }

fib(index - 1) + fib(index - 2) or fib(index - 2) + fib(index - 1)

Fill in the code to complete the following method for checking whether a string is a palindrome. public static boolean isPalindrome(String s) { return isPalindrome(s, 0, s.length() - 1); } public static boolean isPalindrome(String s, int low, int high) { if (high <= low) // Base case return true; else if (s.charAt(low) != s.charAt(high)) // Base case return false; else return _______________________________; }

isPalindrome(s, low + 1, high - 1)

To get an iterator from a set, you may use the __________ method.

iterator

Suppose List<String> list = new ArrayList<String>. Which of the following operations are correct?

list.add("Red");

What are the base cases in the following recursive method? public static void xMethod(int n) { if (n > 0) { System.out.print(n % 10); xMethod(n / 10); } }

n <= 0

To declare a class named A with a generic type, use

public class A<E> { ... }

Fill in the code to complete the following method for sorting a list. public static void sort(double[] list) { ___________________________; } public static void sort(double[] list, int high) { if (high > 1) { // Find the largest number and its index int indexOfMax = 0; double max = list[0]; for (int i = 1; i <= high; i++) { if (list[i] > max) { max = list[i]; indexOfMax = i; } } // Swap the largest with the last number in the list list[indexOfMax] = list[high]; list[high] = max; // Sort the remaining list sort(list, high - 1); } }

sort(list, list.length - 1)

All the concrete classes in the Java Collections Framework implement _____________.

the Serializable interfaces

What is the output of the following code? import java.util.*; public class Test { public static void main(String[] args) { List<String> list1 = new ArrayList<>(); list1.add("Atlanta"); list1.add("Macon"); list1.add("Savanna"); List<String> list2 = new ArrayList<>(); list2.add("Atlanta"); list2.add("Macon"); list2.add("Savanna"); List<String> list3 = new ArrayList<>(); list3.add("Macon"); list3.add("Savanna"); list3.add("Atlanta"); System.out.println(list1.equals(list2) + " " + list1.equals(list3)); } }

true false

Which of the following statements are true?

-Every recursive method must have a base case or a stopping condition. -Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case. -Infinite recursion can occur if recursion does not reduce the problem in a manner that allows it to eventually converge into the base case.

Which of the following statements are true?

-Generic type information is present at compile time. -Generic type information is not present at runtime. -You cannot create an instance using a generic class type parameter. -You cannot create an array using a generic class type parameter. -You cannot create an array using a generic class.

Which of the following data types have iterators?

-HashSet -TreeSet -ArrayList -LinkedList -LinkedHashSet

Which of the following statements are true about recursive methods?

-Recursive methods usually take more memory space than non-recursive methods. -A recursive method can always be replaced by a non-recursive method. -In some cases, however, using recursion enables you to give a natural, straightforward, simple solution to a program that would otherwise be difficult to solve.

Which of the following statements are true?

-The Collection interface is the root interface for manipulating a collection of objects. -The Collection interface provides the basic operations for adding and removing elements in a collection. -The AbstractCollection class is a convenience class that provides partial implementation for the Collection interface. -Some of the methods in the Collection interface cannot be implemented in the concrete subclass. In this case, the method would throw java.lang.UnsupportedOperationException, a subclass of RuntimeException. -All interfaces and classes in the Collections framework are declared using generic type since JDK 1.5.

Which of the following statements are true?

-The Comparable interface contains the compareTo method with the signature "public int compareTo(E)". -The Comparator interface contains the compare method with the signature "public int compare(E, E)". - A Comparable object can compare this object with the other object. - A Comparator object contains the compare method that compares two objects.

Which of the following statements are correct?

-When you create an array using new int[10], an array object is created with ten integers of value 0. -When you create an ArrayList using new ArrayList(), an ArrayList object is created with no elements in the ArrayList object. -When you create an array using int[] x = new int[10], x.length() is 10.

Which of the following are true?

-You can insert an element anywhere in an arraylist. -You can insert an element anywhere in a linked list. -You can use a linked list to improve efficiency for adding and removing elements at the beginning of a list. -You should use an array list if your application does not require adding and removing elements at the beginning of a list.

Which of the following methods are in java.util.List?

-add(int index, E element) -get() -set() -remove() -subList()

Which of the following methods are in the Collection interface?

-clear() -isEmpty() -size() -add() -addAll() -contains(): boolean -containsAll(): boolean -remove(): boolean -removeAll(): boolean

You can use the methods in the Collections class to

-find the maximum object in a collection based on the compareTo method. -find the maximum object in a collection using a Comparator object.

java.util.Vector is a subtype of __________.

-java.util.AbstractList -java.util.List

java.util.Stack is a subclass of __________.

-java.util.AbstractList -java.util.Vector -java.util.List

Which of the following statements are true?

-java.util.LinkedList implements the java.util.Queue interface. -java.util.PriorityQueue implements the java.util.Queue interface.

Which of the following statements are true?

-java.util.List inherits all the methods from java.util.Collection. Additionally, it contains new methods for manipulating a list. -The AbstractList class provides a partial implementation for the List interface. -ArrayList is a concrete implementation of List using an array. -LinkedList is a concrete implementation of List using a linked list. LinkedList contains all the methods in List and additional new methods for manipulating a linked list. -ListIterator is a subinterface of Iterator and it provides the methods to support bi-directional traversal of a list.

Suppose List list = new ArrayList(). Which of the following operations are correct?

-list.add("Red"); -list.add(new Integer(100)); -list.add(new java.util.Date()); -list.add(new ArrayList());

Suppose ArrayList<Double>list = new ArrayList<>(). Which of the following statements are correct?

-list.add(5.5); // 5.5 is automatically converted to new Double(5.5) -list.add(3.0); // 3.0 is automatically converted to new Double(3.0) -Double doubleObject = list.get(0); // No casting is needed -double d = list.get(1); // Automatically converted to double

To create a set that consists of string elements "red", "green", and "blue", use

-new HashSet<String>(Arrays.asList(new String[]{"red", "green", "blue"})) -new LinkedHashSet<String>(Arrays.asList(new String[]{"red", "green", "blue"}))

When you create an ArrayList using ArrayList<String> x = new ArrayList<>(2), ________

-no elements are currently in the array list. -the array list capacity is currently 2.

The method header is left blank in the following code. Fill in the header. public class GenericMethodDemo { public static void main(String[ ] args ) { Integer[ ] integers = {1, 2, 3, 4, 5}; String[ ] strings = {"London", "Paris", "New York", "Austin"}; print(integers); print(strings); } __________________________________________ { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); } }

-public static void print(Object[] list) -public static <E> void print(E[] list)

You can use the methods in the Arrays class to

-sort an array. -do a binary search on an array.

Suppose ArrayList x contains three strings [Beijing, Singapore, Tokyo]. Which of the following methods will cause runtime errors?

-x.set(3, "New York"); -x.get(3) -x.remove(3)

Which of the following statements are true?

Collections.shuffle(list) randomly reorders the elements in the list. -Collections.shuffle(list, Random) randomly reorders the elements in the list with a specified Random object. -If list1 and list2 are identical, the two lists may be different after invoking Collections.shuffle(list1) and Collections.shuffle(list2). -If list1 and list2 are identical, the two lists are still identical after invoking Collections.shuffle(list1, new Random(3)) and Collections.shuffle(list2, new Random(3)) with the same Random object.

Which of the following is correct to sort the elements in a list lst?

Collections.sort(lst)

Fill in the most appropriate code in the blanks in the MyInt class? public class MyInt implements _______ { int id; public MyInt(int id) { this.id = id; } public String toString() { return String.valueOf(id); } public int compareTo(_______ arg0) { if (id > arg0.id) return 1; else if (id < arg0.id) return -1; else return 0; } }

Comparable<MyInt> / MyInt

What is the output for the following code? import java.util.*; public class Test { public static void main(String[] args) { Set<A> set = new HashSet<>(); set.add(new A()); set.add(new A()); set.add(new A()); set.add(new A()); System.out.println(set); } } class A { int r = 1; public String toString() { return r + ""; } public int hashCode() { return r; } }

[1, 1, 1, 1]

What is the output of the following code? ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.remove(2); System.out.println(list);

[1, 2]

Suppose set s1 is [1, 2, 5] and set s2 is [2, 3, 6]. After s1.removeAll(s2), s1 is __________.

[1, 5]

What is the output for the following code? import java.util.*; public class Test { public static void main(String[] args) { Set<A> set = new HashSet<A>(); set.add(new A()); set.add(new A()); set.add(new A()); set.add(new A()); System.out.println(set); } } class A { int r = 1; public String toString() { return r + ""; } public boolean equals(Object o) { return this.r == ((A)o).r; } public int hashCode() { return r; } }

[1]

Suppose list list1 is [1, 2, 5] and list list2 is [2, 3, 6]. After list1.addAll(list2), list2 is __________.

[2, 3, 6]

Suppose set s1 is [1, 2, 5] and set s2 is [2, 3, 6]. After s1.addAll(s2), s2 is __________.

[2, 3, 6]

What is the output of the following code? import java.util.*; public class Test { public static void main(String[] args) { ArrayList<Student> list = new ArrayList<>(); list.add(new Student("Peter", 65)); list.add(new Student("Jill", 50)); list.add(new Student("Sarah", 34)); Collections.sort(list); System.out.print(list + " "); Collections.sort(list, new StudentComparator1()); System.out.println(list); } static class StudentComparator1 implements Comparator<Student> { public int compare(Student s1, Student s2) { return s1.name.compareTo(s2.name); } } static class Student implements Comparable<Student> { String name; int age; Student(String name, int age) { this.name = name; this.age = age; } public int compareTo(Student s) { return this.age - s.age; } public String toString() { return "[" + name + ", " + age + "]"; } } }

[[Sarah, 34], [Jill, 50], [Peter, 65]] [[Jill, 50], [Peter, 65], [Sarah, 34]]

Fill in the code to complete the following method for computing factorial. /** Return the factorial for a specified index */ public static long factorial(int n) {i f (n == 0) // Base case return 1; elsereturn _____________; // Recursive call }

n * factorial(n - 1) or factorial(n - 1) * n

In the following method, what is the base case? static int xMethod(int n) { if (n == 1) return 1; else return n + xMethod(n - 1); }

n is 1

The __________ method in the Queue interface retrieves, but does not remove, the head of this queue, returning null if this queue is empty.

peek()

The __________ method in the Queue interface retrieves and removes the head of this queue, or null if this queue is empty.

poll()

To declare a class named A with two generic types, use

public class A<E, F> { ... }

To declare an interface named A with two generic types, use

public interface A<E, F> { ... }

To declare an interface named A with a generic type, use

public interface A<E> { ... }

Fill in the code to complete the following method for binary search. public static int recursiveBinarySearch(int[] list, int key) { int low = 0; int high = list.length - 1; return __________________________; } public static int recursiveBinarySearch(int[] list, int key, int low, int high) { if (low > high) // The list has been exhausted without a match return -low - 1; // Return -insertion point - 1 int mid = (low + high) / 2; if (key < list[mid]) return recursiveBinarySearch(list, key, low, mid - 1); else if (key == list[mid]) return mid; else return recursiveBinarySearch(list, key, mid + 1, high); }

recursiveBinarySearch(list, key, low, high)

The __________ method in the Queue interface retrieves and removes the head of this queue and throws an exception if this queue is empty.

remove()

If you use the javac command to compile a program that contains raw type, what would the compiler do?

report warning and generate a class file if no other errors in the program.

If two objects o1 and o2 are equal, what are the values for o1.equals(o2) and o1.hashCode() == o2.hashCode()?

true true

Which method do you use to test if an element is in a set or list named x?

x.contains(element)

Which method do you use to remove an element from a set or list named x?

x.remove(element)

Which method do you use to find the number of elements in a set or list named x?

x.size()

Suppose a list contains {"red", "green", "red", "green"}. What is the list after the following code? String element = "red"; for (int i = 0; i < list.size(); i++) if (list.get(i).equals(element)) { list.remove(element); i--; }

{"green", "green"}

Suppose a list contains {"red", "green", "red", "green"}. What is the list after the following code? String element = "red"; for (int i = list.size() - 1; i >= 0; i--) if (list.get(i).equals(element)) list.remove(element);

{"green", "green"}

Suppose a list contains {"red", "green", "red", "green"}. What is the list after the following code? list.remove("red");

{"green", "red", "green"}


Ensembles d'études connexes

Biochemistry Exam 3 Study Guide Questions

View Set

Chapter 33 - Equal Opportunity in Employment

View Set

AP World History Unit 6 Test Strayer

View Set

Urinary Quiz/Disorders and medications

View Set

International Management - Hub 2

View Set