Java Reference
In-Depth Information
Answers to Review Questions
1. E. The HashSet and HashMap classes do not provide ordering or sorting of items, so they
are not good choices in this scenario. A PriorityQueue is used for processing items based
on a priority, which is not relevant to our needs. The Arrays class is not a collections class;
it is a utility class with only static methods. An ArrayList can be ordered and sorted easily
using the Collections class, which makes it a good choice for this scenario. Therefore, the
answer is E.
2. B. Because each element has a unique string associated with its value, a map is the best
choice, so C, D, and E are incorrect. A HashMap does not provide specifi c ordering, so A is
incorrect. A TreeMap is always sorted in natural order, and because it implements
NavigableMap, it contains a descending iterator. Therefore, the best choice for this scenario
is TreeMap and the answer is B.
3. E. The code does not compile, so A, B, and C are incorrect. D is also incorrect; line 9
compiles fi ne because the code is not using generics and any Object can be added to list.
Line 10 does not compile because list contains Object references and the for-each loop
is attempting to assign them to String. Therefore, the answer is E.
4. D. The code does not compile, so A, B, and C are incorrect. E is also incorrect; line 10
compiles fi ne because list contains String objects. Line 9 does not compile because list
is instantiated using generics; only String objects can be added to list and 7 is an int.
Therefore, the answer is D.
5. C. Here is the sequence of events:
1.
Line 4 adds 4 to values at index 0.
2.
Line 5 adds 5 to values at index 1.
3.
Line 6 replaces 5 with 6 at index 1.
4.
Line 7 removes 4 from index 0, leaving only the 6 in values.
The for-each loop only iterates one time and 6 is displayed, so the answer is C.
6. B. The code compiles fi ne, so E is incorrect. The strings “hello“, “hi“, and “ola” are
pushed onto the stack. The call to pop on line 14 removes “ola” from the stack. The call to
peek on line 15 returns “hi” but does not remove it from the stack. That leaves “hello”
and “hi” on the stack, and they are iterated in that order. Therefore, the output is hellohi
and the answer is B.
7. A, C, and D. A is valid because Vector implements List and the <String> generics are
identical. B does not compile because
<Integer> is not compatible with <Number>. (There
is no implied polymorphism with generic types.) C is valid because HashMap implements
Map and Integer is a child of Number. D is valid because Exception is a parent class of
ClassCastException. E is not valid because LinkedHashSet does not implement List.
Search WWH ::




Custom Search