CS Final

¡Supera tus tareas y exámenes ahora con Quizwiz!

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

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

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

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

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

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

Which of the following methods are in the Collection interface?

A. remove(o: Object): boolean B. removeAll(c: Collection<?>): boolean

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

Suppose the keys 3, 4, 45, 21, 92, 12 are inserted into a BST in this order. What is the preorder traversal of the elements after deleting 45 from the tree?

3 4 21 12 92

Suppose the keys 3, 4, 45, 21, 92, 12 are inserted into a BST in this order. What is the preorder traversal of the elements?

3 4 45 21 12 92

Which of the following is incorrect?

A constructor may be static.

The time complexity for the Sieve of Eratosthenes algorithm is ________.

O(n^(1.5)/logn)

The gift-wrapping algorithm for finding a convex hull takes ______________ time.

O(n^2)

The time complexity for the insertion sort algorithm in the text is ________.

O(n^2)

The time complexity for the selection sort algorithm in the text is ________.

O(n^2)

The Graham?s algorithm for finding a convex hull takes ______________ time.

O(nlogn)

Which of the following statements regarding abstract methods is false?

A. An abstract class can have instances created using the constructor of the abstract class.

The average-time complexity for heap sort is _________

O(nlogn)

The average-time complexity for merge sort is _________.

O(nlogn)

The average-time complexity for quick sort is _________.

O(nlogn)

The time complexity for the the closest pair of points problem using divide-and-conquer is ________.

O(nlogn)

The worst-time complexity for heap sort is _________

O(nlogn)

The worst-time complexity for merge sort is _________.

O(nlogn)

The time complexity of the BFS algorithm is O(|E| + |V|).

true

The time complexity of the DFS algorithm is O(|E| + |V|).

true

True or False? Assume N and hashCode are positive and N is an integer of power of 2, hashCode % N is the same as hashCode & (N - 1).

true

True or False? Two objects have the same hash codes if they are equal.

true

True or False? You can traverse the elements in a BST using a for-each loop.

true

Every object has the hashCode() method.

true

What is the output of running class C?class A {public A() {System.out.println("The default constructor of A is invoked");}}class B extends A {public B() {System.out.println("The default constructor of B is invoked");}}public class C {public static void main(String[] args) {B b = new B();}}

"The default constructor of A is invoked" followed by "The default constructor of B is invoked"

Fill in the code to complete the following method for checking whether a string is a palindrome. public static boolean isPalindrome(String s) { if (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

Show the output of the following codepublic class Test1 {public static void main(String[] args) {System.out.println(f2(2, 0));}public static int f2(int n, int result) {if (n == 0)return 0;elsereturn f2(n - 1, n + result);}}

0

1 & 3 is _________.

1

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

10

For a sorted list of 1024 elements, a binary search takes at most _______ comparisons.

11

Suppose the keys 3, 4, 45, 21, 92, 12 are inserted into a BST in this order. What is the postorder traversal of the elements?

12 21 92 45 4 3

How many times is the fib method in Listing 18.2 invoked for fib(5)?

15

How many times is the recursive moveDisks method invoked for 4 disks?

15

Suppose a graph is created in the following code. What is the output of the following code? String[] vertices = {"Atlanta", "Dallas", "Chicago", "New York", "Seattle"}; int[][] edges = {{0, 1}, {0, 2},{1, 0}, {1, 2}, {1, 3}, {1, 4},{2, 0}, {2, 1}, {2, 3},{3, 1}, {3, 2}, {3, 4},{4, 1}, {4, 3}}; Graph<String> graph1 = new UnweightedGraph<>(vertices, edges); System.out.println("The index of vertex Chicago is: "+ graph1.getIndex("Chicago"));

2

Suppose a list is {2, 9, 5, 4, 8, 1}. After the first pass of bubble sort, the list becomes

2, 5, 4, 8, 1, 9

For an Integer object with value 20, what is its hashCode?

20

Which of the following complexity is O(nlogn)?

23nlogn + 50 C. 45n + 45nlogn + 503

Suppose a graph is created in the following code. What is the degree of vertex 3 in the graph?Integer[] vertices = {0, 1, 2, 3, 4}; int[][] edges = {{0, 1}, {0, 2},{1, 0}, {1, 2}, {1, 3}, {1, 4},{2, 0}, {2, 1}, {2, 3},{3, 1}, {3, 2}, {3, 4},{4, 1}, {4, 3}}; Graph<Integer> graph1 = new UnweightedGraph<>(vertices, edges); System.out.println("The degree of vertex 3: "+ graph1.getDegree(3));

3

Suppose the keys 3, 4, 45, 21, 92, 12 are inserted into a BST in this order. What is the preorder traversal of the elements after inserting 2 into the tree?

3 2 4 45 21 12 92

Suppose the keys 3, 4, 45, 21, 92, 12 are inserted into a BST in this order. What is the inorder traversal of the elements?

3 4 12 21 45 92

1 << 2 is _________.

4

Suppose you choose the first element as a pivot in the list {5 2 9 3 8 4 0 1 6 7}. Using the partition algorithm in the book, what is the new list after the partition?

4 2 1 3 0 5 8 9 6 7

Suppose a graph is created in the following code. What is the number of vertices in the graph?Integer[] vertices = {0, 1, 2, 3, 4};int[][] edges = {{0, 1}, {0, 2},{1, 0}, {1, 2}, {1, 3}, {1, 4},{2, 0}, {2, 1}, {2, 3},{3, 1}, {3, 2}, {3, 4},{4, 1}, {4, 3}}; Graph<Integer> graph1 = new UnweightedGraph<>(vertices, edges); System.out.println("The number of vertices in graph1: "+ graph1.getSize());

5

How many times is the factorial method in Listing 18.1 invoked for factorial(5)?

6

How many times is the recursive moveDisks method invoked for 3 disks?

7

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 statements are true?

A heap is a complete binary tree. B. Each node is greater than or equal to any of its children. C. A binary tree is complete if every level of the tree is full except that the last level may not be full and all the leaves on the last level are placed left-most.

________ is a data structure to store data in sequential order.

A list

What is correct about a pivot?

A pivot can be chosen arbitrarily. C. A pivot divides a list into two sublists, the elements in the first list are no larger than the pivot and the elements in the second

Which of the following statements are true?

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

Which of the following statements are true?

A. A class should describe a single entity and all the class operations should logically fit together to support a coherent purpose. D. The constructors may be protected.

Which of the following is poor design?

A. A data field is derived from other data fields in the same class. B. A method must be invoked after/before invoking another method in the same class. C. A method is an instance method, but it does not reference any instance data fields or invoke instance methods. D. A parameter is passed from a constructor to initialize a static data field.

Which of the following statements are true?

A. A method can be overloaded in the same class. D. If a method overrides another method, these two methods must have the same signature. E. A method in a subclass can overload a method in the superclass.

Which of the following are true?

A. A stack can be viewed as a special type of list, where the elements are accessed, inserted, and deleted only from the end, called the top, of the stack. B. A queue represents a waiting list. A queue can be viewed as a special type of list, where the elements are inserted into the end (tail) of the queue, and are accessed and deleted from the beginning (head) of the queue. C. Since the insertion and deletion operations on a stack are made only at the end of the stack, you can use either an ArrayList or a LinkedList. However, ArrayList has less overhead than LinkedList. D. Since deletions are made at the beginning of the list, it is more efficient to implement a queue using a LinkedList than an ArrayList.

Which of the following statements are true?

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

Why is the analysis often for the worst case?

A. Best-case is not representative. B. Worst-case is not representative, but worst-case analysis is very useful. You can show that the algorithm will never be slower than the worst-case. C. Average-case analysis is ideal, but difficult to perform, because it is hard to determine the relative probabilities and distributions of various input instances for many problems.

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);

A. Code fragment A runs faster than code fragment B.

Which of the following statements are true?

A. Collections.shuffle(list) randomly reorders the elements in the list. B. Collections.shuffle(list, Random) randomly reorders the elements in the list with a specified Random object. C. If list1 and list2 are identical, the two lists may be different after invoking Collections.shuffle(list1) and Collections.shuffle(list2). D. 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 statements is correct?

A. Comparable<String> c = new String("abc"); B. Comparable<String> c = "abc";

Which of the following statements are true?

A. Every recursive method must have a base case or a stopping condition. B. Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case. C. 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?

A. Generic type information is present at compile time. B. Generic type information is not present at runtime. C. You cannot create an instance using a generic class type parameter. D. You cannot create an array using a generic class type parameter. E. You cannot create an array using a generic class.

Which of the following statements is correct?

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

Which of the following statements are true?

A. Inheritance models the is-a relationship between two classes. B. A strong is-a relationship describes a direct inheritance relationship between two classes. C. A weak is-a relationship describes that a class has certain properties. D. A strong is-a relationship can be represented using class inheritance. E. A weak is-a relationship can be represented using interfaces.

Which of the following statements is incorrect?

A. Integer i = 4.5;

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

A. Iterator

Which of the following statements are true?

A. MyArrayList and MyLinkedList are two concrete implementations of MyList. B. MyArrayList is implemented using an array. The array is dynamically created. If the capacity of the array is exceeded, create a new larger array and copy all the elements from the current array to the new array. C. MyLinkedList is implemented using a linked structure. D. A linked structure consists of nodes. Each node is dynamically created to hold an element. All the nodes are linked together to form a list.

In the implementation of MyLinkedList, which of the following are true?

A. MyLinkedList contains all the methods defined in MyList. Additionally, MyLinkedList defines several new methods that are appropriate for processing a linked list. B. MyArrayList does not introduce new methods. All the methods in MyArrayList are defined in MyList. C. You can use a linked list to improve efficiency for adding and removing an element anywhere in a list. D. You should use an array list if your application does not require adding and removing an element anywhere in a list.

In the implementation of BST, which of the following are true?

A. Node is defined as an inner class inside BST. B. Node is defined as a static inner class inside BST because it does not reference any instance data fields in BST. C. Node has a property named left that links to the left subtree and a property named right that links to the right subtree and a property named right D. BST contains a property named root. If tree is empty, root is null.

In the implementation of MyLinkedList, which of the following are true?

A. Node is defined as an inner class inside MyLinkedList. B. Node is defined as a static inner class inside MyLinkedList because it does not reference any instance data fields in MyLinkedList. C. Node has a property named next that links to the node after this node. D. Node has a property named element that stores an element.

Which of the following statements are true?

A. Override the equals(Object) method in the Object class whenever possible. B. Override the toString() method in the Object class whenever possible. C. A public default no-arg constructor is assumed if no constructors are defined explicitly. D. You should follow standard Java programming style and naming conventions. Choose informative names for classes, data fields, and methods.

Analyze the following code.// Program 1public class Test {public static void main(String[] args) {Object a1 = new A();Object a2 = new A();System.out.println(((A)a1).equals((A)a2));}}class A {int x;public boolean equals(A a) {return this.x == a.x;}}// Program 2public class Test {public static void main(String[] args) {A a1 = new A();A a2 = new A();System.out.println(a1.equals(a2));}}class A {int x;public boolean equals(A a) {return this.x == a.x;}}

A. Program 1 displays true and Program 2 displays true

Which of the following operations are supported by a list?

A. Retrieve an element from this list. B. Insert a new element to this list. C. Delete an element from this list. D. Find how many elements are in this list. E. Find whether an element is in this list.

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

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

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

A. poll()

Which of the following statements are true?

A. The Collection interface is the root interface for manipulating a collection of objects. B. The Collection interface provides the basic operations for adding and removing elements in a collection. C. The AbstractCollection class is a convenience class that provides partial implementation for the Collection interface. D. 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. E. All interfaces and classes in the Collections framework are declared using generic type since JDK 1.5.

Which of the following statements are true?

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

Which of the following statements are true?

A. The String class implements Comparable. B. The Date class implements Comparable. C. The Double class implements Comparable. D. The BigInteger class implements Comparable

Assume Cylinder is a subtype of Circle. Analyze the following code:Circle c = new Circle (5);Cylinder c = cy;

A. The code has a compile error.

Analyze the following code:ArrayList<String> list = new ArrayList<String>();list.add("Beijing");list.add("Tokyo");list.add("Shanghai");list.set(3, "Hong Kong");

A. The last line in the code causes a runtime error because there is no element at index 3 in the array list. C. If you replace the last line by list.add(3, "Hong Kong"), the code will compile and run fine.

The GeometricObject and Circle classes are defined in this chapter. Analyze the following code. Which statements are correct? public class Test { public static void main(String[] args) { GeometricObject x = new Circle(3);GeometricObject y = (Circle)(x.clone()); System.out.println(x);System.out.println(y);}}

A. The program has a compile error because the clone() method is protected in the Object class. B. After you override the clone() method and make it public in the Circle class, the problem can compile and run just fine, but y is null if Circle does not implement the Cloneable interface. C. To enable a Circle object to be cloned, the Circle class has to override the clone() method and implement the java.lang.Cloneable interface. D. If GeometricObject implements Cloneable and Circle overrides the clone() method, the clone() method will work fine to clone Circle objects.

Which of the following statements are true?

A. To override a method, the method must be defined in the subclass using the same signature and compatible return type as in its superclass. B. Overloading a method is to provide more than one method with the same name but with different signatures to distinguish them. C. It is a compile error if two methods differ only in return type in the same class. D. A private method cannot be overridden. If a method defined in a subclass is private in its superclass, the two methods are completely unrelated. E. A static method cannot be overridden. If a static method defined in the superclass is redefined in a subclass, the method defined in the superclass is hidden

Which of the following statements are correct?

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

Which of the following are true?

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

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

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

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

A. add(int index, E element) B. get(int index) C. set(int index, E element) D. remove(int index) E. subList(int fromIndex, int toIndex)

Which of the following methods are in the Collection interface?

A. add(o: E) B. addAll(c: Collection<? extends E>) C. contains(o: Object): boolean D. containsAll(c: Collection<?>): boolean

Assume Calendar calendar = new GregorianCalendar(). __________ returns the month of the year.

A. calendar.get(Calendar.MONTH)

Which of the following methods are in the Collection interface?

A. clear() B. isEmpty() C. size()

In LiveExample 18.9, to draw three smaller triangles recursively, the program invokes:

A. displayTriangles(order - 1, p1, p12, p31); B. displayTriangles(order - 1, p12, p2, p23); C. displayTriangles(order - 1, p31, p23, p3);

What is the output of the following code?public class Test {public static void main(String[] args) {Object o1 = new Object();Object o2 = new Object();System.out.print((o1 == o2) + " " + (o1.equals(o2)));}}

A. false false

You can use the methods in the Collections class to

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

Which of the following statements are true?

A. java.util.LinkedList implements the java.util.Queue interface. E. java.util.PriorityQueue implements the java.util.Queue interface.

Which of the following statements are true?

A. java.util.List inherits all the methods from java.util.Collection. Additionally, it contains new methods for manipulating a list. B. The AbstractList class provides a partial implementation for the List interface. C. ArrayList is a concrete implementation of List using an array. D. 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. E. 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?

A. list.add("Red"); B. list.add(new Integer(100)); C. list.add(new java.util.Date()); D. list.add(new ArrayList());

In the implementation of MyArrayList, which of the following are true?

A. size indicates the number of elements in the list. B. capacity is the length of the array used to store the elements in the list. D. size is reduced by 1 if an element is deleted from the list.

What is the output of the following code?

A. true false

Suppose ArrayList x contains two strings [Beijing, Singapore]. Which of the following method will cause the list to become [Beijing]?

A. x.remove("Singapore") C. x.remove(1)

Which statements are most accurate regarding the following classes?class A {private int i;protected int j;}class B extends A {private int k;protected int m;}

An object of B contains data fields i, j, k, m.

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<>();

Suppose A is an abstract class, B is a concrete subclass of A, and both A and B have a no-arg constructor. Which of the following is correct?

B. A a = new B(); D. B b = new B();

Suppose A is an interface, B is a concrete class with a no-arg constructor that implements A. Which of the following is correct?

B. A a = new B(); D. B b = new B();

Which of the following statements are true?

B. A subclass is usually extended to contain more functions and more detailed information than its superclass. C. "class A extends B" means A is a subclass of 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;

B. Code fragment B runs faster than code fragment A.

The getValue() method is overridden in two ways. Which one is correct?I:public class Test {public static void main(String[] args) {A a = new A();System.out.println(a.getValue());}}class B {public String getValue() {return "Any object";}}class A extends B {public Object getValue() {return "A string";}}II:public class Test {public static void main(String[] args) {A a = new A();System.out.println(a.getValue());}}class B {public Object getValue() {return "Any object";}}class A extends B {public String getValue() {return "A string";}}

B. II

Which statements are most accurate regarding the following classes?class A {private int i;protected int j;}class B extends A {private int k;protected int m;// some methods omitted}

B. In the class B, an instance method can only access j, k, m.

In the implementation of MyLinkedList, which of the following are true?

B. MyLinkedList has the properties named first and last to point to the nodes in a linked list. C. If a linked list is empty, first is null and last is null. E. last.next is always null.

Which of the following statements are true?

B. Recursive methods usually take more memory space than non-recursive methods. C. A recursive method can always be replaced by a non-recursive method. D. 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.

Analyze the following code:public class Test {public static void main(String[] args) {new B();}}class A {int i = 7;public A() {System.out.println("i from A is " + i);}public void setI(int i) {this.i = 2 * i;}}class B extends A {public B() {setI(20);// System.out.println("i from B is " + i);}@Overridepublic void setI(int i) {this.i = 3 * i;}}

B. The constructor of class A is called and it displays "i from A is 7".

Analyze the following code:public class Test1 {public Object max(Object o1, Object o2) {if ((Comparable)o1.compareTo(o2) >= 0) {return o1;}else {return o2;}}}

B. The program has a compile error because o1 is an Object instance and it does not have the compareTo method. D. The program would compile if ((Comparable)o1.compareTo(o2) >= 0) is replaced by (((Comparable)o1).compareTo(o2) >= 0).

Analyze the following code:public class A extends B {}class B {public B(String s) {}}

B. The program has a compile error because the default constructor of A invokes the default constructor of B, but B does not have a default constructor. D. The program would compile fine if you add the following constructor into A: A(String s) { super(s); }

Suppose you create a class Square to be a subclass of GeometricObject. Analyze the following code:class Square extends GeometricObject {double length;Square(double length) {GeometricObject(length);}}

B. The program has a compile error because you attempted to invoke the GeometricObject class's constructor illegally.

Analyze the following code:public class Test extends A { public static void main(String[] args) {Test t = new Test();t.print();}}class A {String s;A(String s) {this.s = s;}public void print() {System.out.println(s);}}

B. The program has an implicit default constructor Test(), but it cannot be compiled, because its super class does not have a default constructor. The program would compile if the constructor in the class A were removed. C. The program would compile if a default constructor A(){ } is added to class A explicitly.

Given the following classes and their objects:class C1 {};class C2 extends C1 {};class C3 extends C1 {};C2 c2 = new C2();C3 c3 = new C3();Analyze the following statement:c2 = (C2)((C1)c3);

B. You will get a runtime error because you cannot cast objects from sibling classes.

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);

B. [1, 2]

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 YYYYYYYY { while (!stack1.isEmpty())stack2.push(stack1.pop()); } }

B. add(GenericStack<? extends T> stack1, GenericStack<T> stack2) C. add(GenericStack<T> stack1, GenericStack<? super T> stack2) D. add(GenericStack<T> stack1, GenericStack<Object> stack2)?

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

B. c.iterator()

In the implementation of MyArrayList, which of the following are true?

B. capacity never reduces. C. Inside MyArrayList, a regular array is used to store elements. D. If the current capacity equals to size, capacity is doubled when a new element is added to MyArrayList

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;elsereturn f2(n - 1, n + result);}}

B. f2 is tail recursion, but f1 is not

Object-oriented programming allows you to derive new classes from existing classes. This is called ____________.

B. inheritance

Which of the following are Java keywords?

B. instanceof

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); }}

B. n <= 0

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

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

Which of the following declares an abstract method in an abstract Java class?

B. public abstract void method();

The equals method is defined in the Object class. Which of the following is correct to override it in the String class?

B. public boolean equals(Object other)

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

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

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

B. remove()

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

B. report warning and generate a class file

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

B. 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));}}

B. true false

Invoking _________ returns the first element in an ArrayList x.

B. x.get(0)

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

B. x.remove(element)

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

B. x.set(2, "New York"); C. x.get(2) D. x.remove(2)

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

B. x.set(3, "New York"); C. x.get(3) D. x.remove(3)

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

B. {"green", "red", "green"}

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

B. {"green", "red", "green"}

Suppose an ArrayList list contains {"red", "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);

B. {"red", "green"}

The ________ approach searches for a candidate solution incrementally, abandoning that option as soon as it determines that the candidate cannot possibly be a valid solution, and then looks for a new candidate.

Backtracking

The java.lang.Number and its subclasses are introduced in Chapter 11. Analyze the following code.Number numberRef = new Integer(0);Double doubleRef = (Double)numberRef;

C. A runtime class casting exception occurs, since numberRef is not an instance of Double.

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));

C. AC

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

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

Which of the following statements is false?

C. If you compile a class with errors, a .class file is created for the class.

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

C. Iterable

In the implementation of MyStack and MyQueue, which of the following are true?

C. MyStack contains an array list for storing elements. D. MyQueue contains a linked list for storing elements.

Analyze the following code:Integer[] c = {3, 5};java.util.Collections.shuffle(c);System.out.println(java.util.Arrays.toString(c));

C. The code has a compile error on Collections.shuffle(c). c cannot be an array.

Assume Cylinder is a subtype of Circle. Analyze the following code:Cylinder cy = new Cylinder(1, 1);Circle c = cy;

C. The code is fine.

Which of the following are incorrect?

C. The constructors in an abstract class are private. D. You may declare a final abstract class. E. An interface may contain constructors.

Analyze the following code. Which of the following statements is correct? public class Test { public static void main(String[] args) {Number x = new Integer(3); System.out.println(x.intValue()); System.out.println(x.compareTo(new Integer(4))); }}

C. The program has a compile error because x does not have the compareTo method.

A class design requires that a particular member variable must be accessible by any subclasses of this class, but otherwise not by classes which are not members of the same package. What should be done to achieve this?

C. The variable should be marked protected.

Analyze the following code:public class Test {public static void main(String[] args) {Object a1 = new A();Object a2 = new Object();System.out.println(a1);System.out.println(a2);}}class A {int x;@Overridepublic String toString() {return "A's x is " + x;}}

C. When executing System.out.println(a2), the toString() method in the Object class is invoked. D. When executing System.out.println(a1), the toString() method in the A class is invoked.

Which of the statements regarding the super keyword is incorrect?

C. You can use super.super.p to invoke a method in superclass's parent class.

The output from the following code is __________.java.util.ArrayList<String> list = new java.util.ArrayList<String>();list.add("New York"); java.util.ArrayList<String> list1 = list;list.add("Atlanta"); list1.add("Dallas"); System.out.println(list1);

C. [New York, Atlanta, Dallas]

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 + "]";}}}

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

What is the output of the following code?public class Test {public static void main(String[] args) {String s1 = new String("Java");String s2 = new String("Java");System.out.print((s1 == s2) + " " + (s1.equals(s2)));}}

C. false true

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

C. fib(index - 1) + fib(index - 2) D. fib(index - 2) + fib(index - 1)

Which of the following classes cannot be extended?

C. final class A { }

java.util.Stack is a subclass of __________.

C. java.util.AbstractList D. java.util.Vector E. java.util.List

java.util.Vector is a subtype of __________.

C. java.util.AbstractList E. java.util.List

Given the following code, find the compile error.public class Test {public static void main(String[] args) {m(new GraduateStudent());m(new Student());m(new Person());m(new Object());}public static void m(Student x) {System.out.println(x.toString());}}class GraduateStudent extends Student {}class Student extends Person {@Overridepublic String toString() {return "Student";}}class Person extends Object {@Overridepublic String toString() {return "Person";}}

C. m(new Person()) causes an error D. m(new Object()) causes an error

Given two reference variables t1 and t2, if t1.equals(t2) is true, t1 == t2 ___________.

C. may be true or false

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) { if (n == 0) // Base case return 1; else return _____________; // Recursive call}

C. n * factorial(n - 1) D. factorial(n - 1) * n

You can create an ArrayList using _________.

C. new ArrayList<>()

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

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

The Rational class in this chapter is defined as a subclass of java.lang.Number. Which of the following expressions is correct?

C. new Rational(5, 4).doubleValue(); E. new Rational(5, 4).intValue();

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

C. peek()

You can use the methods in the Arrays class to

C. sort an array. E. do a binary search on an array.

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 listlist[indexOfMax] = list[high];list[high] = max;// Sort the remaining listsort(list, high - 1); }}

C. sort(list, list.length - 1)

What is the output of the following code?

C. true true

Suppose ArrayList x contains two strings [Beijing, Singapore]. Which of the following methods will cause the list to become [Beijing, Chicago, Singapore]?

C. x.add(1, "Chicago")

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--; }

C. {"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);

C. {"green", "green"}

Suppose an ArrayList list contains {"red", "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--;}

C. {"green"}

Suppose an ArrayList list contains {"red", "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);

C. {"green"}

Suppose list1 is a MyArrayList and list2 is a MyLinkedList. 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 is more efficient that code fragment B.

Suppose list1 is an MyArrayList and list2 is a MyLinkedList. Both contains 1 million double values. Analyze the following code:A:for (int i = 0; i < 100000; i++)list1.add(i);B:for (int i = 0; i < 100000; i++)list2.add(i);

Code fragment A runs as fast as code fragment B

Suppose list1 is an MyArrayList and list2 is a MyLinkedList. Both contains 1 million double values. Analyze the following code:A:while (list1.size() > 0)list1.remove(size() - 1);B:while (list2.size() > 0)list2.remove(size() - 1);

Code fragment A runs faster than code fragment B.

Suppose list1 is a MyArrayList and list2 is a MyLinkedList. Both contains 1 million double values. Analyze the following code: A:while (list1.size() > 0)list1.remove(0); B:while (list2.size() > 0)list2.remove(0);

Code fragment B runs faster than code fragment A

Suppose list1 is an MyArrayList and list2 is a MyLinkedList. Both contains 1 million double values. Analyze the following code:A:for (int i = 0; i < 100000; i++)list1.add(0, i);B:for (int i = 0; i < 100000; i++)list2.add(0, 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

Which of the following statements are true?

Collections.nCopies(int, Object) returns a new list that consists of n copies of the 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

Assume an employee can work for only one company. What is the best suitable relationship between Company and Employee?

Composition

Which of the following statements is false?

D. A method with no visibility modifier can be accessed by a class in a different package.

_______ is not a reference type.

D. A primitive type

Analyze the following code.Number[] numberArray = new Integer[2];numberArray[0] = new Double(1.5);

D. At runtime, new Integer[2] is assigned to numberArray. This makes each element of numberArray an Integer object. So you cannot assign a Double object to it.

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

D. Collections.max(Arrays.asList(names))

Analyze the following code. Which of the following statements is correct? public class Test {public static void main(String[] args) {Number x = new Integer(3); System.out.println(x.intValue()); System.out.println((Integer)x.compareTo(new Integer(4)));}}

D. The program has a compile error because the member access operator (.) is executed before the casting operator.

What modifier should you use on a class so that a class in the same package can access it but a class (including a subclass) in a different package cannot access it?

D. Use the default modifier.

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

D. Vector

Show the output of running the class Test in the following code lines: interface A { } class C { } class B extends D implements A { } public class Test { public static void main(String[] args) {B b = new B(); if (b instanceof A) System.out.println("b is an instance of A"); if (b instanceof C) System.out.println("b is an instance of C"); }} class D extends C { }

D. b is an instance of A followed by b is an instance of C.

Given the following code, which of the following expressions evaluates to false?class C1 {}class C2 extends C1 { }class C3 extends C2 { }class C4 extends C1 {}C1 c1 = new C1();C2 c2 = new C2();C3 c3 = new C3();C4 c4 = new C4();

D. c4 instanceof C2

Assume Calendar calendar = new GregorianCalendar(). __________ returns the week of the year.

D. calendar.get(Calendar.WEEK_OF_YEAR)

Which of the following is a correct interface?

D. interface A { void print();}

You can assign _________ to a variable of Object[] type.

D. new String[100] E. new java.util.Date[100]

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(); } }

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

Analyze the following code:public class Test {public static void main(String[] args) {String s = new String("Welcome to Java");Object o = s;String d = (String)o;}}

D. s, o, and d reference the same String object.

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

D. x.contains(element)

Invoking _________ returns the number of the elements in an ArrayList x.

D. x.size()

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

D. x.size()

______________ approach divides the problem into subproblems, solves the subproblems, then combines the solutions of the subproblems to obtain the solution for the entire problem. Unlike the ________ approach, the subproblems in the divide-and-conquer approach don?t overlap. A subproblem is like the original problem with a smaller size, so you can apply recursion to solve the problem.

Divide-and-conquer/dynamic programming

Which of the following statements is false?

Dynamic binding can apply to static methods.

______________ approach is the process of solving subproblems, then combining the solutions of the subproblems to obtain an overall solution. This naturally leads to a recursive solution. However, it would be inefficient to use recursion, because the subproblems overlap. The key idea behind dynamic programming is to solve each subproblem only once and store the results for subproblems for later use to avoid redundant computing of the subproblems.

Dynamic programming

Which of the following statements regarding abstract methods is false?

E. A data field can be declared abstract.

What is the output of running class Test? public class Test { public static void main(String[] args) {new Circle9();}} public abstract class GeometricObject { protected GeometricObject() { System.out.print("A");} protected GeometricObject(String color, boolean filled) {System.out.print("B");}} public class Circle9 extends GeometricObject {/** No-arg constructor */ public Circle9() { this(1.0);System.out.print("C");}/** Construct circle with a specified radius */ public Circle9(double radius) { this(radius, "white", false); System.out.print("D");}/** Construct a circle with specified radius, filled, and color */ public Circle9(double radius, String color, boolean filled) {super(color, filled); System.out.print("E");}}

E. BEDC

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);}}}

E. Program A produces the output 4 3 2 1 and Program B prints 4 3 2 1 1 1 .... 1 infinitely.

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

E. [2, 3, 6]

Assume Calendar calendar = new GregorianCalendar(). __________ returns the number of days in a month.

E. calendar.getActualMaximum(Calendar.DAY_OF_MONTH)

Invoking _________ removes all elements in an ArrayList x.

E. x.clear()

The relationship between an interface and the class that implements it is

Inheritance

What is the best suitable relationship between Employee and Faculty?

Inheritance

MyLinkedList is more efficient than MyArrayList for the following operations:

Insert/delete an element in the beginning of the list

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

Iterable

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

_______ measures how full the hash table is.

Load factor

A heap is represented using an array. Is the array {1 2 4 5 9 3} a heap?

No

The time complexity for the Towers of Hanoi algorithm in the text is ________.

O(2^n)

The time complexity for the recursive Fibonacci algorithm in the text is ________.

O(2^n)

The time complexity for the Euclid?s algorithm is ________.

O(logn)

The best-time complexity for bubble sort is _____________.

O(n)

The best-time complexity for insertion sort is _____________.

O(n)

The time complexity for deleing an element into a binary search tree is _______.

O(n)

The time complexity for inserting an element into a binary search tree is _______.

O(n)

The time complexity for searching an element in a binary search tree is _______.

O(n)

The time complexity for the algorithm using the dynamic programming approach is ________.

O(n)

The time to merge two sorted lists of size n is _________.

O(n)

The worst-time complexity for bubble sort is _____________.

O(n*n)

The worst-time complexity for insertion sort is _____________.

O(n*n)

The worst-time complexity for quick sort is _________.

O(n*n)

_____________ is to find an open location in the hash table in the event of collision.

Open addressing

What is the output of the following code?public class Test {public static void main(String[] args) {new Person().printPerson();new Student().printPerson();}}class Student extends Person {private String getInfo() {return "Student";}}class Person {private String getInfo() {return "Person";}public void printPerson() {System.out.println(getInfo());}}

Person Person

What is the output of the following code?public class Test {public static void main(String[] args) {new Person().printPerson();new Student().printPerson();}}class Student extends Person {@Overridepublic String getInfo() {return "Student";}}class Person {public String getInfo() {return "Person";}public void printPerson() {System.out.println(getInfo());}}

Person Student

Which data structure is appropriate to store patients in an emergency room?

Priority Queue

Analyze the following code.// Program 1:public class Test {public static void main(String[] args) {Object a1 = new A();Object a2 = new A();System.out.println(a1.equals(a2));}}class A {int x;public boolean equals(A a) {return this.x == a.x;}}// Program 2:public class Test {public static void main(String[] args) {A a1 = new A();A a2 = new A();System.out.println(a1.equals(a2));}}class A {int x;public boolean equals(A a) {return this.x == a.x;}}

Program 1 displays false and Program 2 displays true

Analyze the following code.// Program 1:public class Test {public static void main(String[] args) {Object a1 = new A();Object a2 = new A();System.out.println(a1.equals(a2));}}class A {int x;public boolean equals(Object a) {return this.x == ((A)a).x;}}// Program 2:public class Test {public static void main(String[] args) {Object a1 = new A();Object a2 = new A();System.out.println(a1.equals(a2));}}class A {int x;public boolean equals(A a) {return this.x == a.x;}}

Program 1 displays true and Program 2 displays false

Which data structure is appropriate to store customers in a clinic for taking flu shots?

Queue

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

Suppose the rule of the party is that the participants who arrive later will leave earlier. Which data structure is appropriate to store the participants?

Stack

Which of the following statements are true?

The Fibonacci series begins with 0 and 1, and each subsequent number is the sum of the preceding two numbers in the series.

Analyze the following code:Double[] array = {1, 2, 3};ArrayList<Double> list = new ArrayList<>(Arrays.asList(array));System.out.println(list);

The code has a compile error because an integer such as 1 is automatically converted into an Integer object, but the array element type is Double.

Analyze the following code:double[] array = {1, 2, 3};ArrayList<Double> list = new ArrayList<>(Arrays.asList(array));System.out.println(list);

The code has a compile error because asList(array) requires that the array elements are objects.

Analyze the following code:double[] c = {1, 2, 3};System.out.println(java.util.Collections.max(c));

The code has a compile error on Collections.max(c). c cannot be an array.

Analyze the following code:public class Test {public static void main(String[] args) {new B();}}class A {int i = 7;public A() {setI(20);System.out.println("i from A is " + i);}public void setI(int i) {this.i = 2 * i;}}class B extends A {public B() {// System.out.println("i from B is " + i);}@Overridepublic void setI(int i) {this.i = 3 * i;}} A. The co

The constructor of class A is called and it displays "i from A is 60".

Analyze the following code:public class Test { public static void main(String[] args) {B b = new B();b.m(5);System.out.println("i is " + b.i);}}class A {int i;public void m(int i) {this.i = i;}}class B extends A {public void m(String s) {}}

The method m is not overridden in B. B inherits the method m from A and defines an overloaded method m in B.

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: 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 code.public class Test { public static void main(String[] args) { java.util.Date x = new java.util.Date(); java.util.Date y = x.clone();System.out.println(x = y); }}

The program has a compile error because the return type of the clone() method is java.lang.Object.

The java.util.Calendar and java.util.GregorianCalendar classes are introduced in Chapter 11. Analyze the following code. Which of the following statements is correct? 1. import java.util.*; 2. public class Test { 3. public static void main(String[] args) { 4. Calendar[] calendars = new Calendar[10]; 5. calendars[0] = new Calendar(); 6. calendars[1] = new GregorianCalendar(); 7. } 8. }

The program has a compile error on Line 5 because java.util.Calendar is an abstract class.

The Rational class in this chapter extends java.lang.Number and implements java.lang.Comparable. Analyze the following code. 1. public class Test { 2. public static void main(String[] args) { 3. Number[] numbers = {new Rational(1, 2), new Integer(4), new Double(5.6)}; 4. java.util.Arrays.sort(numbers); 5. } 6. }

The program has a runtime error because the compareTo methods in Rational, Integer, and Double classes do not compare the value of one type with a value of another type.

Analyze the following code.1. public class Test { 2. public static void main(String[] args) { 3. Fruit[] fruits = {new Fruit(2), new Fruit(3), new Fruit(1)}; 4. java.util.Arrays.sort(fruits); 5. } 6. } class Fruit { private double weight; public Fruit(double weight) { this.weight = weight; }}

The program has a runtime error on Line 4 because the Fruit class does not implement the java.lang.Comparable interface and the Fruit objects are not comparable.

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

Show the output of the following code:String[] array = {"red", "green", "blue"};ArrayList<String> list = new ArrayList<>(Arrays.asList(array));list.add(0, "red");System.out.println(list);

["red", "red", "green", "blue"]

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]

Suppose a graph is created in the following code. Using the bfs algorithm in the text, what is the output for the path from 4 to 0?Integer[] vertices = {0, 1, 2, 3, 4}; int[][] edges = {{0, 1}, {0, 2},{1, 0}, {1, 2}, {1, 3}, {1, 4},{2, 0}, {2, 1}, {2, 3},{3, 1}, {3, 2}, {3, 4},{4, 1}, {4, 3}}; Graph<Integer> graph1 = new UnweightedGraph<>(vertices, edges); AbstractGraph<Integer>.Tree bfs = graph1.bfs(0); System.out.println(bfs.getPath(4));

[4, 1, 0]

Suppose a graph is created in the following code. Using the dfs algorithm in the text, what is the output for the path from 4 to 0?Integer[] vertices = {0, 1, 2, 3, 4}; int[][] edges = {{0, 1}, {0, 2},{1, 0}, {1, 2}, {1, 3}, {1, 4},{2, 0}, {2, 1}, {2, 3},{3, 1}, {3, 2}, {3, 4},{4, 1}, {4, 3}}; Graph<Integer> graph1 = new UnweightedGraph<>(vertices, edges); AbstractGraph<Integer>.Tree dfs = graph1.dfs(0); System.out.println(dfs.getPath(4));

[4, 3, 2, 1, 0]

The output from the following code is __________. java.util.ArrayList<String> list = new java.util.ArrayList<String>(); list.add("New York"); java.util.ArrayList<String> list1 = (java.util.ArrayList<String>)(list.clone()); list.add("Atlanta"); list1.add("Dallas"); System.out.println(list1);

[New York, Dallas]

Which of the following class definitions defines a legal abstract class?

abstract class A { abstract void unfinished(); }

An input that results in the shortest execution time is called the _____________.

best-case input

A __________ (with no duplicate elements) has the property that for every node in the tree the value of any node in its left subtree is less than the value of the node and the value of any node in its right subtree is greater than the value of the node.

binary search tree

The _______ search of a graph first visits a vertex, then all its adjacent vertices, then all the vertices adjacent to those vertices, and so on.

breadth-first

The _________ is to visit the nodes level by level. First visit the root, then all children of the root from left to right, then grandchildren of the root from left to right, and so on.

breadth-first traversal

A _________ is the one in which every two pairs of vertices are connected.

complete graph

O(1) is ________.

constant time

The _______ of a node is the length of the path from the root to the node.

depth

The _______ search of a graph first visits a vertex, then it recursively visits all the vertices adjacent to that vertex.

depth-first

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()

True or False? Two objects are equal if they are equal.

false

A Huffman tree is constructed using the ____________ algorithm.

greedy

On an average, linear search searches

half of the list

The most efficient algorithm for sorting integer keys is __________.

heap sort

The _______ of a nonempty tree is the length of the path from the root node to its furthest leaf + 1.

height

The ________ is to visit the left subtree of the current node first, then the current node itself, and finally the right subtree of the current node.

inorder traversal

What is the return type value for the hashCode() method?

int

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)

The ________ of a path is the number of the edges in the path.

length

When a collision occurs during the insertion of an entry to a hash table, ______ finds the next available location sequentially.

linear probing

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

list.add("Red");

A ____ is an edge that links a vertex to itself.

loop

A hashing function __________.

maps a key to an index in the hash table

What is the number of edges in a tree of n vertices?

n - 1

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.

What is the number of edges in a complete graph of n vertices?

n(n-1)/2

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

no

If two vertices are connected by two or more edges, these edges are called

parallel edge

If each key is mapped to a different index in the hash table, it is called _______.

perfect hashing

The _________ is to visit the left subtree of the current node first, then the right subtree of the current node, and finally the current node itself.

postorder traversal

The _________ is to visit the current node first, then the left subtree of the current node, and finally the right subtree of the current node

preorder traversal

The visibility of these modifiers increases in this order:

private, none (if no modifier is used), protected, and public.

What modifier should you use on the members of a class so that they are not accessible to another class in a different package, but are accessible to any subclasses in any package?

protected

The __________ algorithm does not compare keys.

radix sort

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 matchreturn -low - 1; // Return -insertion point - 1int 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)

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.

The __________ places all entries with the same hash index into the same location, rather than finding new locations.

separate chaining scheme

Given two reference variables t1 and t2, if t1 == t2 is true, t1.equals(t2) must be ___________.

true

If two strings are equal, the two strings have the same hashCodes.

true

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

Encapsulation means ______________.

that a class can extend another class

Inheritance means ______________.

that a class can extend another class

Composition means ______________.

that a class contains a data field that references another object

Polymorphism means ___________

that a variable of supertype can refer to a subtype object

What is the number of iterations in the following loop: int count = 5; while (count < n) { count = count + 3; }

the ceiling of (n - 5) / 3

To add a new node, you need to start a process by first placing it as _______ and move it up to maintain the heap property.

the last node in the heap

To remove the root, you need to start a process by first placing _______ to the place of the root and move it down to maintain the heap property.

the last node in the heap

Analyzing algorithm efficiency is ________.

to estimate their growth function

A new element is always inserted into a leaf node.

true

A collision occurs _____________.

when two or more keys are mapped to the same hash value

A heap is represented using an array. Is the array {64 42 59 32 39 44} a heap?

yes

Does <? super Number> represent a superclass of Number?

yes

Is ArrayList<?> same as ArrayList<? extends Object>?

yes

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

yes

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

yes

Suppose a heap is stored in an array list as follows: {100, 55, 92, 23, 33, 81}. The parent of 81 is _______.

{103, 55, 100, 23, 33, 81, 92}

Using the partition algorithm to partition an array {5, 8, 10, 3, 4, 19, 2} for a quick sort, what is the resulting array after the partition?

{3, 2, 4, 5, 10, 19, 8}


Conjuntos de estudio relacionados

Philosophy: Quiz on Utilitarianism

View Set

Ozone Depletion, Indoor & Outdoor Air Pollution

View Set

Chapter 25: Management of Patients with complications of Heart disease

View Set

Astronomy Test 1, 2, and 3 MCQ's and Answers

View Set

Ap Gov Exam- "Checks and balances"

View Set