jobs4timesLogo jobs4timesLogo

Collections and Generics

Q: 01 Given:

34. HashMap props = new HashMap();
35. props.put("key45", "some value");
36. props.put("key12", "some other value");
37. props.put("key39", "yet another value");
38. Set s = props.keySet();
39. // insert code here
What, inserted at line 39, will sort the keys in the props HashMap ?
  1. Arrays.sort(s);
  2. s = new TreeSet(s);
  3. Collections.sort(s);
  4. s = new SortedSet(s);
Answer: B

Q: 02 Click the Exhibit button.

Which statement is true about the set variable on line 12 ?
  1. The set variable contains all six elements from the coll collection, and the order is guaranteed to be preserved.
  2. The set variable contains only three elements from the coll collection, and the order is guaranteed to be preserved.
  3. The set variable contains all six elements from the coll collection, but the order is NOT guaranteed to be preserved.
  4. The set variable contains only three elements from the coll collection, but the order is NOT guaranteed to be preserved.
Answer: D

Q: 03 Given:

23. Object [] myObjects = {
24. new Integer(12),
25. new String("foo"),
26. new Integer(5),
27. new Boolean(true)
28. };
29. Arrays.sort(myObjects);
30. for(int i=0; i<myObjects.length; i++) {
31. System.out.print(myObjects[i].toString());
32. System.out.print(" ");
33. }
What is the result ?
  1. Compilation fails due to an error in line 23.
  2. Compilation fails due to an error in line 29.
  3. A ClassCastException occurs in line 29.
  4. A ClassCastException occurs in line 31.
  5. The value of all four objects prints in natural order.
Answer: C

Q: 04 Click the Task button.

Solution:
1.Gen<T>
2.T
3.Gen
4.T
5.T

Q: 05 Click the Task button.

Solution:
1. list.add("foo"); ----------- Compilation fails
2. list = new ArrayList<String>(); ------Compilation succeeds
3.list=new ArrayList<Object>( ); ---- Compilation fails
4. String s = list.get(0); ------ Compilation succeeds
5. Object o = list; ----- Compilation succeeds

Q: 06 Given:

1. public class Person {
2. private String name;
3. public Person(String name) { this.name = name; }
4. public boolean equals(Person p) {
5. return p.name.equals(this.name);
6. }
7. }
Which statement is true?
  1. The equals method does NOT properly override the Object.equals method.
  2. Compilation fails because the private attribute p.name cannot be accessed in line 5.
  3. To work correctly with hash-based data structures, this class must also implement the hashCode method.
  4. When adding Person objects to a java.util.Set collection, the equals method in line 4 will prevent duplicates.
Answer: A

Q: 07 Given:

1. import java.util.*; 
2. public class Old { 
3. public static Object get0(List list) { 
4. return list.get(0); 
5. } 
6. }
Which three will compile successfully? (Choose three.)
  1. Object o = Old.get0(new LinkedList());
  2. Object o = Old.get0(new LinkedList<?>());
  3. String s = Old.get0(new LinkedList<String>());
  4. Object o = Old.get0(new LinkedList<Object>());
  5. String s = (String)Old.get0(new LinkedList<String>());
Answer: A, D, E

Q: 08 Given:

1. import java.util.*; 
2. public class Example { 
3. public static void main(String[] args) { 
4. // insert code here 
5. set.add(new Integer(2)); 
6. set.add(new Integer(1)); 
7. System.out.println(set); 
8. } 
9. }
Which code, inserted at line 4, guarantees that this program will output [1, 2] ?
  1. Set set = new TreeSet();
  2. Set set = new HashSet();
  3. Set set = new SortedSet();
  4. List set = new SortedList();
  5. Set set = new LinkedHashSet();
Answer: A

Q: 09 Given:

11. public static Collection get() { 
12. Collection sorted = new LinkedList(); 
13. sorted.add("B"); sorted.add("C"); sorted.add("A"); 
14. return sorted; 
15. } 
16. public static void main(String[] args) { 
17. for (Object obj: get()) { 
18. System.out.print(obj + ", "); 
19. } 
20. }
What is the result ?
  1. A, B, C,
  2. B, C, A,
  3. Compilation fails.
  4. The code runs with no output.
  5. An exception is thrown at runtime.
Answer: B

Q:10 given Click the Task button.

Solution:
  1. Compilation of the first statement succeeds ,but compilation fails due to an error in the second statement.
  2. Compilation fails due to an error in the first statement
  3. Compilation succeeds
  4. Compilation succeeds

Q: 11 Given:

11. public static Iterator reverse(List list) {
12. Collections.reverse(list);
13. return list.iterator();
14. }
15. public static void main(String[] args) {
16. List list = new ArrayList();
17. list.add("1"); list.add("2"); list.add("3");
18. for (Object obj: reverse(list))
19. System.out.print(obj + ", ");
20. }
What is the result ?
  1. 3, 2, 1,
  2. 1, 2, 3,
  3. Compilation fails.
  4. The code runs with no output.
  5. An exception is thrown at runtime.
Answer: C

Q: 12 Click the Task button.

============does not compile================ 1.m1(listO ); 2.m2(listB); 3.m2(listO); =====compiles and runs with out error========= 1.m1(listA); 2.m1(listB); 3.m2(listA);

Q: 13 Given:

1. import java.util.*;
2. public class PQ {
3. public static void main(String[] args) {
4. PriorityQueue<String> pq = new PriorityQueue<String>();
5. pq.add("carrot");
6. pq.add("apple");
7. pq.add("banana");
8. System.out.println(pq.poll() + ":" + pq.peek());
9. }
10. }
What is the result ?
  1. apple:apple
  2. carrot:apple
  3. apple:banana
  4. banana:apple
  5. carrot:carrot
  6. carrot:banana
Answer: C

Q: 14 Given:

1. import java.util.*; 
2. public class WrappedString { 
3. private String s; 
4. public WrappedString(String s) { this.s = s; } 
5. public static void main(String[] args) { 
6. HashSet<Object> hs = new HashSet<Object>(); 
7. WrappedString ws1 = new WrappedString("aardvark"); 
8. WrappedString ws2 = new WrappedString("aardvark"); 
9. String s1 = new String("aardvark"); 
10. String s2 = new String("aardvark"); 
11. hs.add(ws1); hs.add(ws2); hs.add(s1); hs.add(s2); 
12. System.out.println(hs.size()); } }
What is the result ?
  1. 0
  2. 1
  3. 2
  4. 3
  5. 4
  6. Compilation fails.
  7. An exception is thrown at runtime.
Answer: D

Q: 15 Given:

11. public class Key { 
12. private long id1; 
13. private long id2; 
14. 
15. // class Key methods 
16. }
A programmer is developing a class Key, that will be used as a key in a standard java.util.HashMap. Which two methods should be overridden to assure that Key works correctly as a key? (Choose two.)
  1. public int hashCode()
  2. public boolean equals(Key k)
  3. public int compareTo(Object o)
  4. public boolean equals(Object o)
  5. public boolean compareTo(Key k)
Answer: A, D

Q: 16 Given a pre-generics implementation of a method:

11. public static int sum(List list) { 
12. int sum = 0; 
13. for ( Iterator iter = list.iterator(); iter.hasNext(); ) { 
14. int i = ((Integer)iter.next()).intValue(); 
15. sum += i; 
16. } 
17. return sum; 
18. } 
Which three changes must be made to the method sum to use generics ? (Choose three.)
  1. remove line 14
  2. replace line 14 with "int i = iter.next();"
  3. replace line 13 with "for (int i : intList) {"
  4. replace line 13 with "for (Iterator iter : intList) {"
  5. replace the method declaration with "sum(List<int> intList)"
  6. replace the method declaration with "sum(List<Integer> intList)"
Answer: A, C, F

Q: 17 Given:

11. // insert code here 
12. private N min, max; 
13. public N getMin() { return min; } 
14. public N getMax() { return max; } 
15. public void add(N added) { 
16. if (min == null || added.doubleValue() < min.doubleValue()) 
17. min = added; 
18. if (max == null || added.doubleValue() > max.doubleValue()) 
19. max = added; 
20. } 
21. } 
Which two, inserted at line 11, will allow the code to compile? (Choose two.)
  1. public class MinMax<?> {
  2. public class MinMax<? extends Number> {
  3. public class MinMax<N extends Object> {
  4. public class MinMax<N extends Number> {
  5. public class MinMax<? extends Object> {
  6. public class MinMax<N extends Integer> {
Answer: D, F

Q: 18 Given:

1. import java.util.*; 
2. 
3. public class LetterASort{ 
4. public static void main(String[] args) { 
5. ArrayList<String> strings = new ArrayList<String>(); 
6. strings.add("aAaA"); 
7. strings.add("AaA"); 
8. strings.add("aAa"); 
9. strings.add("AAaa"); 
10. Collections.sort(strings); 
11. for (String s : strings) { System.out.print(s + " "); } 
12. } 
13. }
What is the result?
  1. Compilation fails.
  2. aAaA aAa AAaa AaA
  3. AAaa AaA aAa aAaA
  4. AaA AAaa aAaA aAa
  5. aAa AaA aAaA AAaa
  6. An exception is thrown at runtime.
Answer: C

Q: 19 Click the Task button.

Solution:
public class NumberNames{
private HashMap< String , Integer> map=
new HashMap< String , Integer >( );
public void put(String name . int Value) {
map.put(name , Value);
}
public Set<String> getNames( ) {
return map.keySet( );
}
}

Q: 20 Which two statements are true about the hashCode method? (Choose two.)

  1. The hashCode method for a given class can be used to test for object equality and object inequality for that class.
  2. The hashCode method is used by the java.util.SortedSet collection class to order the elements within that set.
  3. The hashCode method for a given class can be used to test for object inequality, but NOT object equality, for that class.
  4. The only important characteristic of the values returned by a hashCode method is that the distribution of values must follow a Gaussian distribution.
  5. The hashCode method is used by the java.util.HashSet collection class to group the elements within that set into hash buckets for swift retrieval.
Answer: C, E

Q: 21 Click the Task button.

Solution:
1.implements
2.comparable
3.public
4.coompareTo(Object o)
5. i

Q: 22

A programmer has an algorithm that requires a java.util.List that provides an efficient implementation of add(0, object), but does NOT need to support quick random access.

What supports these requirements ?
  1. java.util.Queue
  2. java.util.ArrayList
  3. java.util.LinearList
  4. java.util.LinkedList
Answer: D

Q: 23 Click the Task button.

Solution: ( 1)-------( 3) ( 2)---------(1) (3)-------(4) (4)---------(2)

Q: 24 Given:

10. interface A { void x(); }
11. class B implements A { public void x() {} public void y() {} }
12. class C extends B { public void x() {} }
And:
20. java.util.List<A> list = new java.util.ArrayList<A>();
21. list.add(new B());
22. list.add(new C());
23. for (A a : list) {
24. a.x();
25. a.y();
26. }
What is the result ?
  1. The code runs with no output.
  2. An exception is thrown at runtime.
  3. Compilation fails because of an error in line 20.
  4. Compilation fails because of an error in line 21.
  5. Compilation fails because of an error in line 23.
  6. Compilation fails because of an error in line 25.
Answer: F

Q: 25 Click the Task button.

Solution: 4. Compilation of the first statement succeeds ,but compilation fails due to an error in the second statement. 5. Compilation fails due to an error in the first statement 6. Compilation succeeds 7. Compilation succeeds

Q: 26 Click the Task button.

Solution:
1. list.add("foo"); ----------- Compilation fails
2. list = new ArrayList<String>(); ------Compilation succeeds
3.list=new ArrayList<Object>( ); ---- Compilation fails
4. String s = list.get(0); ------ Compilation succeeds
5. Object o = list; ----- Compilation succeeds

Q: 27 Given:

1. public class Drink implements Comparable {
2. public String name;
3. public int compareTo(Object o) {
4. return 0;
5. }
6. }
and:
20. Drink one = new Drink();
21. Drink two = new Drink();
22. one.name= "Coffee";
23. two.name= "Tea";
23. TreeSet set = new TreeSet();
24. set.add(one);
25. set.add(two);

A programmer iterates over the TreeSet and prints the name of each Drink object.

What is the result ?
  1. Tea
  2. Coffee
  3. Coffee Tea
  4. Compilation fails.
  5. The code runs with no output.
  6. An exception is thrown at runtime.
Answer: B

Q:28 Click the Task button.

Solutions: compilation fails: Public void takeList(ArrayList<Animal> list) { } Public void takeList(ArrayList<Object> list) { } compilation Succeeds All the remaining

Q: 29 Click the Task button.

Solution:
import java.util.*;
public class TestGenericConversion {
public static void main(String s[ ]){
List<String> list=new LinkedList<String>( );
list.add("one");
list.add("two");
System.out.println(list.get(0).length(); }
} }

Q: 30 Given:

10. abstract public class Employee {
11. protected abstract double getSalesAmount();
12. public double getCommision() {
13. return getSalesAmount() * 0.15;
14. }
15. }
16. class Sales extends Employee {
17. // insert method here
18. }
Which two methods, inserted independently at line 17, correctly complete the Sales class? (Choose two.)
  1. double getSalesAmount() { return 1230.45; }
  2. public double getSalesAmount() { return 1230.45; }
  3. private double getSalesAmount() { return 1230.45; }
  4. protected double getSalesAmount() { return 1230.45; }
Answer: B, D

Q: 31 Given:

13. public static void search(List<String> list) { 
14. list.clear(); 
15. list.add("b"); 
16. list.add("a"); 
17. list.add("c"); 
18. System.out.println(Collections.binarySearch(list, "a")); 
19. } 
What is the result of calling search with a valid List implementation ?
  1. 0
  2. 1
  3. 2
  4. a
  5. b
  6. c
  7. The result is undefined.
Answer: G

Q: 32 Given:

11. public static void append(List list) { list.add("0042"); } 
12. public static void main(String[] args) { 
13. List<Integer> intList = new ArrayList<Integer>(); 
14. append(intList); 
15. System.out.println(intList.get(0)); 
16. } 
What is the result ?
  1. 42
  2. 0042
  3. An exception is thrown at runtime.
  4. Compilation fails because of an error in line 13.
  5. Compilation fails because of an error in line 14.
Answer: B

Q: 33 Given:

11. public class Person { 
12. private name; 
13. public Person(String name) { 
14. this.name = name; 
15. } 
16. public int hashCode() { 
17. return 420; 
18. } 
19. }
Which statement is true ?
  1. The time to find the value from HashMap with a Person key depends on the size of the map.
  2. Deleting a Person key from a HashMap will delete all map entries for all keys of type Person.
  3. Inserting a second Person object into a HashSet will cause the first Person object to be removed as a duplicate.
  4. The time to determine whether a Person object is contained in a HashSet is constant and does NOT depend on the size of the map.
Answer: A

Q: 34

A programmer must create a generic class MinMax and the type parameter of MinMax must implement Comparable.

Which implementation of MinMax will compile ?
  1. class MinMax<E extends Comparable<E>> { E min = null; E max = null; public MinMax() {} public void put(E value) { /* store min or max */ }
  2. class MinMax<E implements Comparable<E>> { E min = null; E max = null; public MinMax() {} public void put(E value) { /* store min or max */ }
  3. class MinMax<E extends Comparable<E>> { <E> E min = null; <E> E max = null; public MinMax() {} public <E> void put(E value) { /* store min or max */ }
  4. class MinMax<E implements Comparable<E>> { <E> E min = null; <E> E max = null; public MinMax() {} public <E> void put(E value) { /* store min or max */ }
Answer: A

Q: 35 Given:

int[] myArray = new int[] {1, 2, 3, 4, 5};

What allows you to create a list from this array ?
  1. List myList = myArray.asList();
  2. List myList = Arrays.asList(myArray);
  3. List myList = new ArrayList(myArray);
  4. List myList = Collections.fromArray(myArray);
Answer: B

Question: 36 Given:

 1. public class Score implements Comparable<Score> { 
 2. private int wins, losses; 
 3. public Score(int w, int 1) { wins = w; losses = 1; } 
 4. public int getWins() { return wins; } 
 5. public int getLosses() { return losses; } 
 6. public String toString() { 
 7. return "<" + wins + "," + losses + ">"; 
 8. } 
 9. // insert code here 
 10. } 
 
Which method will complete this class ?
  1. public int compareTo(Object o) {/*mode code here*/}
  2. public int compareTo(Score other) {/*more code here*/}
  3. public int compare(Score s1,Score s2){/*more code here*/}
  4. public int compare(Object o1,Object o2){/*more code here*/}
Answer: B

Question: 37 Click the Exhibit button.

1. import java.util.*; 
2. class KeyMaster { 
3. public int i; 
4. public KeyMaster(int i) { this.i = i; } 
5. public boolean equals(Object o) { return i == ((KeyMaster)o).i; } 
6. public int hashCode() { return i; } 
7. } 
8. public class MapIt { 
9. public static void main(String[] args) { 
10. Set<KeyMaster> set = new HashSet<KeyMaster>(); 
11. KeyMaster k1 = new KeyMaster(1); 
12. KeyMaster k2 = new KeyMaster(2); 
13. set.add(k1); set.add(k1); 
14. set.add(k2); set.add(k2); 
15. System.out.print(set.size() + ":"); 
16. k2.i = 1; 
17. System.out.print(set.size() + ":"); 
18. set.remove(k1); 
19. System.out.print(set.size() + ":"); 
20. set.remove(k2); 
21. System.out.print(set.size()); 
22. } 
23. }
What is the result ?
  1. 4:4:2:2
  2. 4:4:3:2
  3. 2:2:1:0
  4. 2:2:0:0
  5. 2:1:0:0
  6. 2:2:1:1
  7. 4:3:2:1
Answer: F

Question: 38 Given:

1. import java.util.*; 
2. public class Test { 
3. public static void main(String[] args) { 
4. List<String> strings = new ArrayList<String>(); 
5. // insert code here 
6. } 
7. }
Which four, inserted at line 5, will allow compilation to succeed ? (Choose four.)
  1. String s = strings.get(0);
  2. Iterator i1 = strings.iterator();
  3. String[] array1 = strings.toArray();
  4. Iterator<String> i2 = strings.iterator();
  5. String[] array2 = strings.toArray(new String[1]);
  6. Iterator<String> i3 = strings.iterator<String>();
Answer: A, B, D, E

Question: 39 Given:

classA {} 
class B extends A {} 
class C extends A {} 
class D extends B {}
Which three statements are true ? (Choose three.)
  1. The type List<A> is assignable to List.
  2. The type List<B> is assignable to List<A>.
  3. The type List<Object> is assignable to List<?>.
  4. The type List<D> is assignable to List<? extends B>.
  5. The type List<? extends A> is assignable to List<A>.
  6. The type List<Object> is assignable to any List reference.
  7. The type List<? extends B> is assignable to List<? extends A>.
Answer: C, D, G

Question:40 Given:

11. public void addStrings(List list) { 
12. list.add("foo"); 
13. list.add("bar"); 
14. } 
What must you change in this method to compile without warnings ?
  1. add this code after line 11:
    list = (List<String>) list;
  2. change lines 12 and 13 to:
    list.add<String>("foo"); 
    list.add<String>("bar");
  3. change the method signature on line 11 to:
    public void addStrings(List<? extends String> list) {
  4. change the method signature on line 11 to:
    public void addStrings(List<? super String> list) {
  5. No changes are necessary. This method compiles without warnings.
Answer: D

Question: 41 Given:

1. public class Test { 
2. public <T extends Comparable> T findLarger(T x, T y) { 
3. if(x.compareTo(y) > 0) { 
4. return x; 
5. } else { 
6. return y; 
7. } 
8. } 
9. } 
and: 
22. Test t = new Test();
23. // insert code here
Which two will compile without errors when inserted at line 23 ? (Choose two.)
  1. Object x = t.findLarger(123, "456");
  2. int x = t.findLarger(123, new Double(456));
  3. int x = t.findLarger(123, new Integer(456));
  4. int x = (int) t.findLarger(new Double(123), new Double(456));
Answer: A C

Question: 42 Given:

11. List list = // more code here 
12. Collections.sort(list, new MyComparator()); 
Which code will sort this list in the opposite order of the sort in line 12 ?
  1. Collections.reverseSort(list, new MyComparator());
  2. Collections.sort(list, new MyComparator()); list.reverse();
  3. Collections.sort(list, new InverseComparator( new MyComparator()));
  4. Collections.sort(list, Collections.reverseOrder( new MyComparator()));
Answer: D

Question: 43 Given:

ArrayList a = new ArrayList(); 
containing the values {"1", "2", "3", "4", "5", "6", "7", "8"} 
Which code will return 2 ?
  1. Collections. sort(a, a.reverse()); 
    int result = Collections.binarySearch(a, "6");
  2. Comparator c = Collections.reverseOrder(); 
    Collections.sort(a, c); 
    int result = Collections.binarySearch(a, "6");
  3. Comparator c = Collections.reverseOrder(); 
    Collections.sort(a, c); 
    int result = Collections.binarySearch(a, "6",c);
  4. Comparator c = Collections.reverseOrder(a); 
    Collections.sort(a, c); 
    int result = Collections.binarySearch(a, "6",c);
  5. Comparator c = new InverseComparator(new Comparator()); 
    Collections.sort(a); 
    int result = Collections.binarySearch(a,"6",c);
Answer: C

Question: 44 Given:

11. public class Counter { 
12. public static void main(String[] args) { 
13. int numArgs = /* insert code here */; 
14. } 
15. }
and the command line: java Counter one fred 42 Which code, inserted at line 13, captures the number of arguments passed into the program ?
  1. args.count
  2. args.length
  3. args.count()
  4. args.length()
  5. args.getLength()
Answer: B

Question: 45 Given:

3. import java.util.*; 
4. public class Mapit { 
5. public static void main(String[] args) { 
6. Set<Integer> set = new HashSet<Integer>(); 
7. Integer i1 = 45; 
8. Integer i2 = 46; 
9. set.add(i1); 
10. set.add(i1); 
11. set.add(i2); System.out.print(set.size() + " "); 
12. set.remove(i1); System.out.print(set.size() + " "); 
13. i2 = 47; 
14. set.remove(i2); System.out.print(set.size() + " "); 
15. } 
16. }
What is the result ?
  1. 2 1 0
  2. 2 1 1
  3. 3 2 1
  4. 3 2 2
  5. Compilation fails.
  6. An exception is thrown at runtime.
Answer: B

Question: 46 Given:

12. import java.util.*; 
13. public class Explorer1 { 
14. public static void main(String[] args) { 
15. TreeSet<Integer> s = new TreeSet<Integer>();
16. TreeSet<Integer> subs = new TreeSet<Integer>(); 
17. for(int i = 606; i < 613; i++) 
18. if(i%2 == 0) s.add(i); 
19. subs = (TreeSet)s.subSet(608, true, 611, true); 
20. s.add(609); 
21. System.out.println(s + " " + subs); 
22. } 
23. }
What is the result ?
  1. Compilation fails.
  2. An exception is thrown at runtime.
  3. [608, 609, 610, 612] [608, 610]
  4. [608, 609, 610, 612] [608, 609, 610]
  5. [606, 608, 609, 610, 612] [608, 610]
  6. [606, 608, 609, 610, 612] [608, 609, 610]
Answer: F

Question: 47 Given:

3. import java.util.*; 
4. public class Quest { 
5. public static void main(String[] args) { 
6. String[] colors = {"blue", "red", "green", "yellow", "orange"}; 
7. Arrays.sort(colors); 
8. int s2 = Arrays.binarySearch(colors, "orange"); 
9. int s3 = Arrays.binarySearch(colors, "violet"); 
10. System.out.println(s2 + " " + s3); 
11. } 
12. }
What is the result ?
  1. 2 -1
  2. 2 -4
  3. 2 -5
  4. 3 -1
  5. 3 -4
  6. 3 -5
  7. Compilation fails.
  8. An exception is thrown at runtime.
Answer: C

Question: 48 Given:

5. import java.util.*; 
6. public class SortOf { 
7. public static void main(String[] args) { 
8. ArrayList<Integer> a = new ArrayList<Integer>(); 
9. a.add(1); a.add(5); a.add(3); 

11. Collections.sort(a); 
12. a.add(2); 
13. Collections.reverse(a); 
14. System.out.println(a); 
15. }
16. }
What is the result ?
  1. [1, 2, 3, 5]
  2. [2, 1, 3, 5]
  3. [2, 5, 3, 1]
  4. [5, 3, 2, 1]
  5. [1, 3, 5, 2]
  6. Compilation fails.
  7. An exception is thrown at runtime.
Answer: C

Question: 49 Given:

3. import java.util.*; 
4. public class Hancock { 
5. // insert code here 
6. list.add("foo"); 
7. } 
8. }
Which two code fragments, inserted independently at line 5, will compile without warnings ? (Choose two.)
  1. public void addStrings(List list) {
  2. public void addStrings(List<String> list) {
  3. public void addStrings(List<? super String> list) {
  4. public void addStrings(List<? extends String> list) {
Answer: B, C

Question: 50

Given a class whose instances, when found in a collection of objects, are sorted by using the compareTo() method, which two statements are true? (Choose two.)
  1. The class implements java.lang.Comparable.
  2. The class implements java.util.Comparator.
  3. The interface used to implement sorting allows this class to define only one sort sequence.
  4. The interface used to implement sorting allows this class to define many different sort sequences.
Answer: A,C

51. Given:

import java.util.*; 
class Test { 
public static void main(String[] args) { 
 // insert code here 
 x.add("one"); 
 x.add("two"); 
 x.add("TWO"); 
 System.out.println(x.poll()); 
} }
Which, inserted at // insert code here, will compile? (Choose all that apply.)
  1. List<String> x = new LinkedList<String>();
  2. TreeSet<String> x = new TreeSet<String>();
  3. HashSet<String> x = new HashSet<String>();
  4. Queue<String> x = new PriorityQueue<String>();
  5. ArrayList<String> x = new ArrayList<String>();
  6. LinkedList<String> x = new LinkedList<String>();
Answer:
  • D and F are correct. The poll() method is associated with Queues. The LinkedList class implements the Queue interface.
  • A is incorrect because the List interface does not implement Queue, and the polymorphic instantiation would restrict x to invoking only those methods declared in the List interface. B, C, and E are incorrect, based on the above.

52. Given:

public static void main(String[] args) { 
// INSERT DECLARATION HERE 
for (int i = 0; i <= 10; i++) { 
 List<Integer> row = new ArrayList<Integer>(); 
 for (int j = 0; j <= 10; j++)
    row.add(i * j); 
    table.add(row); 
 } 
 for (List<Integer> row : table) 
  System.out.println(row); 
}
Which statements could be inserted at // INSERT DECLARATION HERE to allow this code to compile and run? (Choose all that apply.)
  1. List<List<Integer>> table = new List<List<Integer>>();
  2. List<List<Integer>> table = new ArrayList<List<Integer>>();
  3. List<List<Integer>> table = new ArrayList<ArrayList<Integer>>();
  4. List<List, Integer> table = new List<List, Integer>();
  5. List<List, Integer> table = new ArrayList<List, Integer>();
  6. List<List, Integer> table = new ArrayList<ArrayList, Integer>();
  7. None of the above.
Answer:
  • B is correct.
  • A is incorrect because List is an interface, so you can't say new List() regardless of any generic types. D, E, and F are incorrect because List only takes one type parameter (a Map would take two, not a List). C is tempting, but incorrect. The type argument <List<Integer>> must be the same for both sides of the assignment, even though the constructor new ArrayList() on the right side is a subtype of the declared type List on the left.

53. Given:

  import java.util.*; 
  class Flubber { 
  public static void main(String[] args) { 
   List<String> x = new ArrayList<String>(); 
   x.add(" x"); 
   x.add("xx"); 
   x.add("Xx"); 
   // insert code here 
   for(String s: x) 
    System.out.println(s); 
  }
}
And the output: xx Xx x Which code, inserted at // insert code here, will produce the preceding output ? (Choose all that apply.)
  1. Collections.sort(x);
  2. Comparable c = Collections.reverse(); Collections.sort(x,c);
  3. Comparator c = Collections.reverse(); Collections.sort(x,c);
  4. Comparable c = Collections.reverseOrder(); Collections.sort(x,c);
  5. Comparator c = Collections.reverseOrder(); Collections.sort(x,c);
Answer:
  • E is correct. Natural ordering would produce output in reverse sequence to that listed. The Collections.reverseOrder() method takes a Comparator not a Comparable to re-sort a Collection.
  • A, B, C, and D are incorrect based on the above.

54. Given:

 10. public static void main(String[] args) { 
 11. Queue<String> q = new LinkedList<String>(); 
 12. q.add("Veronica"); 
 13. q.add("Wallace"); 
 14. q.add("Duncan"); 
 15. showAll(q); 
 16. } 
 17. 
 18. public static void showAll(Queue q) { 
 19. q.add(new Integer(42)); 
 20. while (!q.isEmpty()) 
 21. System.out.print(q.remove() + " "); 
 22. }
 
What is the result ?
  1. Veronica Wallace Duncan
  2. Veronica Wallace Duncan 42
  3. Duncan Wallace Veronica
  4. 42 Duncan Wallace Veronica
  5. Compilation fails.
  6. An exception occurs at runtime.
Answer:
  • B is correct. There is a compiler warning at line 19 because of an unchecked assignment, but other than that everything compiles and runs fine. Although q was originally declared as Queue<String>, in showAll() it's passed as an untyped Queue-nothing in the compiler or JVM prevents us from adding an Integer after that. The add() method puts things at the end of the queue, while remove() takes them from the beginning, so everything prints in the order they were put in.
  • A, C, D, E, and F are incorrect based on the above.

55. Given:

public static void before() { 
 Set set = new TreeSet(); 
 set.add("2"); 
 set.add(3); 
 set.add("1"); 
 Iterator it = set.iterator(); 
 while (it.hasNext()) 
 System.out.print(it.next() + " "); 
}
Which of the following statements are true ?
  1. The before() method will print 1 2
  2. The before() method will print 1 2 3
  3. The before() method will print three numbers, but the order cannot be determined.
  4. The before() method will not compile.
  5. The before() method will throw an exception at runtime.
Answer:
  • E is correct. You can't put both Strings and ints into the same TreeSet. Without generics, the compiler has no way of knowing what type is appropriate for this TreeSet, so it allows everything to compile. At runtime, the TreeSet will try to sort the elements as they're added, and when it tries to compare an Integer with a String it will throw a ClassCastException. Note that although the before() method does not use generics, it does use autoboxing. Watch out for code that uses some new features and some old features mixed together.
  • A, B, C, and D are incorrect based on the above.

56. Given:

import java.util.*; 
class MapEQ { 
 public static void main(String[] args) { 
  Map<ToDos, String> m = new HashMap<ToDos, String>(); 
  ToDos t1 = new ToDos("Monday"); 
  ToDos t2 = new ToDos("Monday"); 
  ToDos t3 = new ToDos("Tuesday"); 
  m.put(t1, "doLaundry"); 
  m.put(t2, "payBills"); 
  m.put(t3, "cleanAttic"); 
  System.out.println(m.size()); 
 } 
}

class ToDos{ 
 String day; 
 ToDos(String d) { day = d; } 
 public boolean equals(Object o) { return ((ToDos)o).day == this.day; } 
  // public int hashCode() {
  return 9; 
 } 
}
Which is correct? (Choose all that apply.)
  1. As the code stands it will not compile.
  2. As the code stands the output will be 2.
  3. As the code stands the output will be 3.
  4. If the hashCode() method is uncommented the output will be 2.
  5. If the hashCode() method is uncommented the output will be 3.
  6. If the hashCode() method is uncommented the code will not compile.
Answer:
  • C and D are correct. If hashCode() is not overridden then every entry will go into its own bucket, and the overridden equals() method will have no effect on determining equivalency. If hashCode() is overridden, then the overridden equals() method will view t1 and t2 as duplicates.
  • A, B, E, and F are incorrect based on the above.

57. Given:

12. public class AccountManager { 
13. private Map accountTotals = new HashMap(); 
14. private int retirementFund; 
15. 
16. public int getBalance(String accountName) { 
17. Integer total = (Integer) accountTotals.get(accountName); 
18. if (total == null) 
19. total = Integer.valueOf(0); 
20. return total.intValue(); 
21. } 
23. public void setBalance(String accountName, int amount) { 
24. accountTotals.put(accountName, Integer.valueOf(amount)); 
25. } }
This class is to be updated to make use of appropriate generic types, with no changes in behavior (for better or worse). Which of these steps could be performed? (Choose three.)
  1. Replace line 13 with private Map<String, int> accountTotals = new HashMap<String, int>();
  2. Replace line 13 with private Map<String, Integer> accountTotals = new HashMap<String, Integer>();
  3. Replace line 13 with private Map<String<Integer>> accountTotals = new HashMap<String<Integer>>();
  4. Replace lines 17–20 with int total = accountTotals.get(accountName); if (total == null) total = 0; return total;
  5. Replace lines 17–20 with Integer total = accountTotals.get(accountName); if (total == null) total = 0; return total;
  6. Replace lines 17–20 with return accountTotals.get(accountName);
  7. Replace line 24 with accountTotals.put(accountName, amount);
  8. Replace line 24 with accountTotals.put(accountName, amount.intValue());
Answer:
  • B , E, and G are correct.
  • A is wrong because you can't use a primitive type as a type parameter.
  • C is wrong because a Map takes two type parameters separated by a comma. D is wrong because an int can't autobox to a null, and F is wrong because a null can't unbox to 0. H is wrong because you can't autobox a primitive just by trying to invoke a method with it.

58.

Given a properly prepared String array containing five elements, which range of results could a proper invocation of Arrays.binarySearch() produce ?
  1. 0 through 4
  2. 0 through 5
  3. -1 through 4
  4. -1 through 5
  5. -5 through 4
  6. -5 through 5
  7. -6 through 4
  8. -6 through 5
Answer:
  • G is correct. If a match is found, binarySearch()will return the index of the element that was matched. If no match is found, binarySearch() will return a negative number that, if inverted and then decremented, gives you the insertion point (array index) at which the value searched on should be inserted into the array to maintain a proper sort.
  • A, B, C, D, E, F, and H are incorrect based on the above.

59. Given:

interface Hungry<E> { 
 void munch(E x); 
} 
interface Carnivore<E extends Animal> extends Hungry<E> {} 
interface Herbivore<E extends Plant> extends Hungry<E> {} 
abstract class Plant {} 
class Grass extends Plant {} 
abstract class Animal {} 
class Sheep extends Animal implements Herbivore<Sheep> {
 public void munch(Sheep x) {} 
} 
class Wolf extends Animal implements Carnivore<Sheep> { 
 public void munch(Sheep x) {} 
}
Which of the following changes (taken separately) would allow this code to compile? (Choose all that apply.)
  1. Change the Carnivore interface to interface Carnivore<E extends Plant> extends Hungry<E> {}
  2. Change the Herbivore interface to interface Herbivore<E extends Animal> extends Hungry<E> {}
  3. Change the Sheep class to class Sheep extends Animal implements Herbivore<Plant> { public void munch(Grass x) {} }
  4. Change the Sheep class to class Sheep extends Plant implements Carnivore<Wolf> { public void munch(Wolf x) {} }
  5. Change the Wolf class to class Wolf extends Animal implements Herbivore<Grass> { public void munch(Grass x) {} }
  6. No changes are necessary.
Answer:
  • B is correct. The problem with the original code is that Sheep tries to implement Herbivore<Sheep> and Herbivore declares that its type parameter E can be any type that extends Plant. Since a Sheep is not a Plant, Herbivore<Sheep> makes no sense- the type Sheep is outside the allowed range of Herbivore's parameter E. Only solutions that either alter the definition of a Sheep or alter the definition of Herbivore will be able to fix this. So A, E, and F are eliminated. B works, changing the definition of an Herbivore to allow it to eat Sheep solves the problem. C doesn't work because an Herbivore<Plant> must have a munch(Plant) method, not munch(Grass). And D doesn't work, because in D we made Sheep extend Plant, now the Wolf class breaks because its munch(Sheep) method no longer fulfills the contract of Carnivore.

60.

Which collection class(es) allows you to grow or shrink its size and provides indexed access to its elements, but whose methods are not synchronized? (Choose all that apply.)
  1. java.util.HashSet
  2. java.util.LinkedHashSet
  3. java.util.List
  4. java.util.ArrayList
  5. java.util.Vector
  6. java.util.PriorityQueue
Answer:
  • D is correct. All of the collection classes allow you to grow or shrink the size of your collection. ArrayList provides an index to its elements. The newer collection classes tend not to have synchronized methods. Vector is an older implementation of ArrayList functionality and has synchronized methods; it is slower than ArrayList.
  • A, B, C, E, and F are incorrect based on the logic described above; Notes: C, List is an interface, and F, PriorityQueue does not offer access by index.

61. Given:

 import java.util.*; 
 public class Group extends HashSet<Person> {
  public static void main(String[] args) {
   Group g = new Group(); 
   g.add(new Person("Hans")); 
   g.add(new Person("Lotte")); 
   g.add(new Person("Jane")); 
   g.add(new Person("Hans")); 
   g.add(new Person("Jane")); 
   System.out.println("Total: " + g.size()); 
  }
 public boolean add(Object o) { 
  System.out.println("Adding: " + o); 
   return super.add(o); 
  } 
 } 
class Person {
 private final String name; 
 public Person(String name) { this.name = name; } 
 public String toString() { return name; } 
}
Which of the following occur at least once when the code is compiled and run ? (Choose all that apply.)
  1. Adding Hans
  2. Adding Lotte
  3. Adding Jane
  4. Total: 3
  5. Total: 5
  6. The code does not compile.
  7. An exception is thrown at runtime.
Answer:
  • F is correct. The problem here is in Group's add() method-it should have been add(Person), since the class extends HashSet<Person>. So this doesn't compile. Pop Quiz: What would happen if you fixed this code, changing add(Object) to add(Person)? Try running the code to see if the results match what you thought.
  • A, B, C, D, E, and G are incorrect based on the above.

62. Given:

import java.util.*; 
class AlgaeDiesel {
 public static void main(String[] args) {
  String[] sa = {"foo", "bar", "baz" };
   // insert method invocations here 
 } 
}
What java.util.Arrays and/or java.util.Collections methods could you use to convert sa to a List and then search the List to find the index of the element whose value is "foo"? (Choose from one to three methods.)
  1. sort()
  2. asList()
  3. toList()
  4. search()
  5. sortList()
  6. contains()
  7. binarySearch()
Answer:
  • A, B, and G are required. The as List() method converts an array to a List. You can find the index of an element in a List with the binarySearch() method, but before you do that you must sort the list using sort().
  • F is incorrect because contains() returns a boolean, not an index. C, D, and E are incorrect, because these methods are not defined in the List interface.

63.

Given that String implements java.lang.CharSequence, and:
 
import java.util.*; 
public class LongWordFinder {
 public static void main(String[] args) {
  String[] array = { "123", "12345678", "1", "12", "1234567890"}; 
  List<String> list = Arrays.asList(array); 
  Collection<String> resultList = getLongWords(list); } 
  // INSERT DECLARATION HERE { 
   Collection<E> longWords = new ArrayList<E>(); 
   for (E word : coll)
    if (word.length() > 6) longWords.add(word); 
     return longWords; 
    } 
}
Which declarations could be inserted at // INSERT DECLARATION HERE so that the program will compile and run? (Choose all that apply.)
  1. public static <E extends CharSequence> Collection<? extends CharSequence> getLongWords(Collection<E> coll)
  2. public static <E extends CharSequence> List<E> getLongWords(Collection<E> coll)
  3. public static Collection<E extends CharSequence> getLongWords(Collection<E> coll)
  4. public static List<CharSequence> getLongWords(Collection<CharSequence> coll)
  5. public static List<? extends CharSequence> getLongWords(Collection<? extends CharSequence> coll)
  6. static public <E extends CharSequence> Collection<E> getLongWords(Collection<E> coll)
  7. static public <E super CharSequence> Collection<E> getLongWords(Collection<E> coll)
Answer:
  • F is correct.
  • A is close, but it's wrong because the return value is too vague. The last line of the method expects the return value to be Collection<String>, not Collection<? extends CharSequence>. B is wrong because longWords has been declared as a Collection<E>, and that can't be implicitly converted to a List<E> to match the declared return value. (Even though we know that longWords is really an ArrayList<E>, the compiler only know what it's been declared as.) C, D, and E are wrong because they do not declare a type variable E (there's no <> before the return value) so the getLongWords() method body will not compile. G is wrong because E super CharSequence makes no sense-super could be used in conjunction with a wildcard but not a type variable like E.

64. Given:

  12. TreeSet map = new TreeSet(); 
  13. map.add("one"); 
  14. map.add("two"); 
  15. map.add("three"); 
  16. map.add("four"); 
  17. map.add("one"); 
  18. Iterator it = map.iterator(); 
  19. while (it.hasNext() ) { 
  20. System.out.print( it.next() + " " ); 
  21. }
  
What is the result ?
  1. Compilation fails.
  2. one two three four
  3. four three two one
  4. four one three two
  5. one two three four one
  6. one four three two one
  7. An exception is thrown at runtime.
  8. The print order is not guaranteed.
Answer:
  • D is correct. TreeSet assures no duplicate entries; also, when it is accessed it will return elements in natural order, which for Strings means alphabetical.
  • A, B, C, E, F, G, and H are incorrect based on the logic described above. Note, even though as of Java 5 you don't have to use an Iterator, you still can.

65. Given a method declared as:

public static <E extends Number> List<? super E> process(List<E> nums) A programmer wants to use this method like this: // INSERT DECLARATIONS HERE output = process(input); Which pairs of declarations could be placed at // INSERT DECLARATIONS HERE to allow the code to compile? (Choose all that apply.)
  1. ArrayList<Integer> input = null; ArrayList<Integer> output = null;
  2. ArrayList<Integer> input = null; List<Integer> output = null;
  3. ArrayList<Integer> input = null; List<Number> output = null;
  4. List<Number> input = null; ArrayList<Integer> output = null;
  5. List<Number> input = null; List<Number> output = null;
  6. List<Integer> input = null; List<Integer> output = null;
  7. None of the above.
Answer:
  • B, E, and F are correct.
  • The return type of process is definitely declared as a List, not an ArrayList, so A and D are wrong. C is wrong because the return type evaluates to List<Integer>, and that can't be assigned to a variable of type List<Number>. Of course all these would probably cause a NullPointerException since the variables are still null-but the question only asked us to get the code to compile.


BACK