Programmer II Chapter 3: Generics and Collections Flashcards

1
Q

What types of method references are there? (4 answers)

A
  1. Static methods
  2. Instance methods on a particular object
  3. Instance methods on a parameter
  4. Constructors
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the result of this code?

15: var heights = new ArrayList < Integer > ();
16: heights.add(null);
17: int h = heights.get(0);

A

NPE at line 17

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What this code prints?

23: List < Integer > numbers = new ArrayList < Integer > ();
24: numbers.add(1);
25: numbers.add(Integer.valueOf(3));
26: numbers.add(Integer.valueOf(5));
27: numbers.remove(1);
28: numbers.remove(Integer.valueOf(5));
29: System.out.println(numbers);

A

[1]

n lines 24 through 26, we add three Integer objects to numbers. The one on line 24 relies on autoboxing to do so, but it gets added just fine. At this point, numbers contains [1, 3, 5].

Line 27 contains the second trick. The remove() method is overloaded. One signature takes an int as the index of the element to remove. The other takes an Object that should be removed. On line 27, Java sees a matching signature for int, so it doesn’t need to autobox the call to the method. Now numbers contains [1,5]. Line 28 calls the other remove() method, and it removes the matching object, which leaves us with just[1]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Which lines contain compilation errors?

List list = new ArrayList < > ();
Map map = new HashMap < > ();
Map < Long,List < Integer > > mapOfLists = new HashMap < > ();

A

All lines compile

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Which lines compile?

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

While they both compile, they are not equivalent. The first one creates an ArrayList < Integer > just like the prior set of examples. The second one creates an ArrayList < Object > . Since there is no generic type specified, it cannot be inferred. Java happily assumes you wanted Object in this scenario

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What data structures allow null values to be added to them?

A

The ones that do not involve sorting

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Will this code compile?

var byWeight = new Comparator < Duck > () {
   public int compareTo(Duck d1, Duck d2) {
      return d1.getWeight()-d2.getWeight();
   }
};
A

No

A Comparator must implement a method named compare()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What will this code print?

public static void printList(List < Object > list) {
for (Object x: list)
System.out.println(x);
}

public static void main(String[] args) {
List < String > keywords = new ArrayList < > ();
   keywords.add("java");
   printList(keywords);
}
A

printList(keywords); will not compile

List < String > cannot be assigned to List < Object > . We know, it doesn’t sound logical. Java is trying to protect us from ourselves with this one.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Will this compile?

3: List < ? super IOException >  exceptions = new ArrayList < Exception > ();
4: exceptions.add(new Exception());
5: exceptions.add(new IOException());
6: exceptions.add(new FileNotFoundException());
A

line 4 will not compile

Line 3 references a List that could be List < IOException > or List < Exception > or List < Object > .
Line 4 does not compile because we could have a List < IOException > and an Exception object wouldn’t fit in there.Line 5 is fine. IOException can be added to any of those types. Line 6 is also fine.

FileNotFoundException can also be added to any of those three types. This is tricky because FileNotFoundException is a subclass of IOException, and the keyword says super. What happens is that Java says, “Well, FileNotFoundException also happens to be an IOException, so everything is fine.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Given these classes

class A {}
class B extends A {}
class C extends B {}

Will this compile?

6: List < ? > list1 = new ArrayList < A > ();
7: List < ? extends A > list2 = new ArrayList < A > ();
8: List < ? super A > list3 = new ArrayList < A > ();

9: List < ? extends B > list4 = new ArrayList < A > ();
10: List < ? super B > list5 = new ArrayList < A > ();
11: List < ? > list6 = new ArrayList < ? extends A > ();

A

Lines 9 and 11 do not compile

Line 6 creates an ArrayList that can hold instances of class A. It is stored in a variable with an unbounded wildcard. Any generic type can be referenced from an unbounded wildcard, making this okay.

Line 7 tries to store a list in a variable declaration with an upper-bounded wildcard. This is okay. You can have ArrayList < A > , ArrayList < B > , or ArrayList < C > stored in that reference. Line 8 is also okay. This time, you have a lower-bounded wildcard. The lowest type you can reference is A. Since that is what you have, it compiles.

Line 9 has an upper-bounded wildcard that allows ArrayList < B > or ArrayList < C > to be referenced. Sinceyou have ArrayList < A > that is trying to be referenced, the code does not compile. Line 10 has a lower-bounded wildcard, which allows a reference to ArrayList < A > , ArrayList < B > , or ArrayList < Object > .

Finally, line 11 allows a reference to any generic type since it is an unbounded wildcard. The problem is that you need to know what that type will be when instantiating the ArrayList. It wouldn’t be useful anyway, because you can’t add any elements to that ArrayList.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Will this compile?

extends T> second(List extends T> list) {
return list.get(0);
}

A

This will not compile

This method does not compile because the return type isn’t actually a type. You are writing the method. You know what type it is supposed to return. You don’t get to specify this as a wildcard

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Given these declarations

class A {}
class B extends A {}

Will this method compile?

 < B extends A >  B third(List < B >  list) {
   return new B();
}
A
This method does not compile. 
< B extends A > says that you want to use B as a type parameter just for this method and that it needs to extend the A class. Coincidentally, B is also the name of a class. It isn't a coincidence. It's an evil trick. Within the scope of the method, B can represent class A, or B. Since B no longer refers to the B class in the method, you can't instantiate it.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Will this compile?

< X > void fifth(List < X super B > list) { }

A

This method does not compile because it tries to mix a method-specific type parameter with a wildcard. A wildcard must have a ? in it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Suppose that you have a collection of products for sale in a database and you need to display those products. The products are not unique. Which of the following collections classes in the java.util package best suits your needs for this scenario?

A. Arrays
B. ArrayList
C. HashMap
D. HashSet
E. LinkedList
A
B. 
The answer needs to implement List because the scenario allows duplicates. Since you need a List, you can eliminate options C and D immediately because HashMap is a Map and HashSet is a Set.Option A, Arrays, is trying to distract you. It is a utility class rather than a Collection. An array is not a collection. This leaves you with options B and E. Option B is a better answer than option E because LinkedList is both a List and a Queue, and you just need a regular List.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Suppose that you need to work with a collection of elements that need to be sorted in their natural order, and each element has a unique text id that you want to use to store and retrieve the record.
Which of the following collections classes in the java.util package best suits your needs for this scenario?

A. ArrayList
B. HashMap
C. HashSet
D. TreeMap
E. TreeSet
F. None of the above
A

D.
The answer needs to implement Map because you are dealing with key/value pairs per the unique id field. You can eliminate options A, C, and E immediately since they are not a Map. ArrayList is a List. HashSet and TreeSet are Sets. Now it is between HashMap and TreeMap. Since the question talks about ordering, you need the TreeMap. Therefore, the answer is option D.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Which of the following are true? (Choose all that apply.)

12: List < ? > q = List.of(“mouse”, “parrot”);
13: var v = List.of(“mouse”, “parrot”);
14:
15: q.removeIf(String::isEmpty);
16: q.removeIf(s -> s.length() == 4);
17: v.removeIf(String::isEmpty);
18: v.removeIf(s -> s.length() == 4);

A. This code compiles and runs without error.
B. Exactly one of these lines contains a compiler error.
C. Exactly two of these lines contain a compiler error.
D. Exactly three of these lines contain a compiler error.
E. Exactly four of these lines contain a compiler error.
F. If any lines with compiler errors are removed, this code runs without throwing an exception.
G. If all lines with compiler errors are removed, this code throws an exception.

A

C, G.
Line 12 creates a List>, which means it is treated as if all the elements are of type Object rather than String. Lines 15 and 16 do not compile since they call the String methods isEmpty()and length(), which are not defined on Object. Line 13 creates a List because var uses the type that it deduces from the context. Lines 17 and 18 do compile. However, List.of() creates an immutable list, so both of those lines would throw an UnsupportedOperationException if run.Therefore, options C and G are correct.

17
Q

What is the result of the following statements?

3: var greetings = new LinkedList < String > ();
4: greetings.offer(“hello”);
5: greetings.offer(“hi”);
6: greetings.offer(“ola”);
7: greetings.pop();
8: greetings.peek();
9: while (greetings.peek() != null)
10: System.out.print(greetings.pop());

A. hello
B. hellohi
C. hellohiola
D. hiola
E. ola
F. The code does not compile.G. An exception is thrown.
A

D.
This is a FIFO (first-in, first-out) queue. On line 7, we remove the first element added, which is”hello”. On line 8, we look at the new first element (“hi”) but don’t remove it. On lines 9 and 10, we remove each element in turn until no elements are left, printing hi and ola together. Note that we don’t use an Iterator to loop through the LinkedList to avoid concurrent modification issues. The order in which the elements are stored internally is not part of the API contract.

18
Q

Which of these statements compile? (Choose all that apply.)

A. HashSet < Number > hs = new HashSet();
B. HashSet < ? super ClassCastException > set = new HashSet < Exception > ();
C. List < > list = new ArrayList < String > ();
D. List < Object > values = new HashSet < Object > ();
E. List < Object > objects = new ArrayList < ? extends Object > ();
F. Map < String, ? extends Number > hm = new HashMap < String, Integer > ();
A
B, F. 
Option A does not compile because the generic types are not compatible. We could say HashSet < ? extends Number > hs2 = new HashSet < Integer > ();. Option B uses a lower bound, so it allows superclass generic types. Option C does not compile because the diamond operator is allowed only on the right side. Option D does not compile because a Set is not a List. Option E does not compile because upper bounds are not allowed when instantiating the type. Finally, option F does compile because the upper bound is on the correct side of the =.
19
Q

What is the result of the following code?

1: public class Hello < T > {
2: T t;
3: public Hello(T t) { this.t = t; }
4: public String toString() { return t.toString(); }
5: private < T > void println(T message) {
6: System.out.print(t + “-“ + message);
7: }
8: public static void main(String[] args) {
9: new Hello < String > (“hi”).println(1);
10: new Hello(“hola”).println(true);
11: } }

A. hi followed by a runtime exception
B. hi-1hola-true
C. The first compiler error is on line 1.
D. The first compiler error is on line 4.
E. The first compiler error is on line 5.
F. The first compiler error is on line 9.
G. The first compiler error is on line 10.

A
B. 
The class compiles and runs without issue. Line 10 gives a compiler warning for not using generics but not a compiler error. Line 4 compiles fine because toString() is defined on the Object class and is therefore always available to call.Line 9 creates the Hello class with the generic type String. It also passes an int to the println() method, which gets autoboxed into an Integer. While the println() method takes a generic parameter of type T, it is not the same < T > defined for the class on line 1. Instead, it is a different T defined as part of the method declaration on line 5. Therefore, the String argument on line 9 applies only to the class. The method can actually take any object as a parameter including autoboxed primitives. Line 10 creates the Hello class with the generic type Object since no type is specified for that instance. It passes a boolean to println(), which gets autoboxed into a Boolean. The result is that hi-1hola-true is printed, making option B correct.
20
Q

Which of the following statements are true? (Choose all that apply.)

3: var numbers = new HashSet < Number > ();
4: numbers.add(Integer.valueOf(86));
5: numbers.add(75);
6: numbers.add(Integer.valueOf(86));
7: numbers.add(null);
8: numbers.add(309L);
9: Iterator iter = numbers.iterator();
10: while (iter.hasNext())
11: System.out.print(iter.next());

A. The code compiles successfully.
B. The output is 8675null309.
C. The output is 867586null309.
D. The output is indeterminate.
E. There is a compiler error on line 3.
F. There is a compiler error on line 9.
G. An exception is thrown.
A

A, D.
The code compiles fine. It allows any implementation of Number to be added. Lines 5 and 8succesfully autobox the primitives into an Integer and Long, respectively. HashSet does not guarantee any iteration order, making options A and D correct.

21
Q

Which of the following can fill in the blank to print [7, 5, 3]? (Choose all that apply.)

3: public class Platypus {
4: String name;
5: int beakLength;
6:
7: // Assume getters/setters/constructors provided
8:
9: public String toString() {return “” + beakLength;}
10:
11: public static void main(String[] args) {
12: Platypus p1 = new Platypus(“Paula”, 3);
13: Platypus p2 = new Platypus(“Peter”, 5);
14: Platypus p3 = new Platypus(“Peter”, 7);
15:
16: List list = Arrays.asList(p1, p2, p3);
17:
18: Collections.sort(list, Comparator.comparing );
19:
20: System.out.println(list);
21: }
22: }

A.
    (Platypus::getBeakLength)
B.
    (Platypus::getBeakLength).reversed()
C.
    (Platypus::getName)
      .thenComparing(Platypus::getBeakLength)
D.
    (Platypus::getName)
      .thenComparing(
         Comparator.comparing(Platypus::getBeakLength)
      .reversed())
E.
    (Platypus::getName)
      .thenComparingNumber(Platypus::getBeakLength)
      .reversed()
F.
    (Platypus::getName)
      .thenComparingInt(Platypus::getBeakLength)
      .reversed()
G.
     None of the above
A

B, F.
We’re looking for a Comparator definition that sorts in descending order by beakLength. Option A is incorrect because it sorts in ascending order by beakLength. Similarly, option C is incorrect because it sorts the beakLength in ascending order within those matches that have the same name.

Option E is incorrect because there is no thenComparingNumber() method.
Option B is a correct answer, as it sorts by beakLength in descending order. Options D and F aretrickier. First notice that we can call either thenComparing() or thenComparingInt() because the former will simply autobox the int into an Integer. Then observe what reversed() applies to.

Option D is incorrect because it sorts by name in ascending order and only reverses the beak length of those with the same name. Option F creates a comparator that sorts by name in ascending order and then by beak size in ascending order. Finally, it reverses the result. This is just what we want, so option F is correct.

22
Q

Which of the answer choices are valid given the following code? (Choose all that apply.)

Map < String, Double > map = new HashMap < > ();

A. map.add("pi", 3.14159);
B. map.add("e", 2L);
C. map.add("log(1)", new Double(0.0));
D. map.add('x', new Double(123.4));
E. None of the above
A

E.
Trick question! The Map interface uses put() rather than add() to add elements to the map. If theseexamples used put(), the answer would be options A and C. Option B is no good because a longcannot be placed inside a Double without an explicit cast. Option D is no good because a char is notthe same thing as a String.

23
Q

What is the result of the following program?

3: public class MyComparator implements Comparator < String > {
4: public int compare(String a, String b) {
5: return b.toLowerCase().compareTo(a.toLowerCase());
6: }
7: public static void main(String[] args) {
8: String[] values = { "123", "Abb", "aab" };
9: Arrays.sort(values, new MyComparator());
10: for (var s: values)
11: System.out.print(s + " ");
12: }
13: }
A. Abb aab 123
B. aab Abb 123
C. 123 Abb aab
D. 123 aab Abb
E. The code does not compile.
F. A runtime exception is thrown.
A

A.
The array is sorted using MyComparator, which sorts the elements in reverse alphabetical order in a case-insensitive fashion. Normally, numbers sort before letters. This code reverses that by calling the compareTo() method on b instead of a.

24
Q

What is the result of the following code?

3: var map = new HashMap < Integer, Integer > (10);
4: for (int i = 1; i <= 10; i++) {
5: map.put(i, i * i);
6: }
7: System.out.println(map.get(4));

A. 16
B. 25
C. Compiler error on line 3.
D. Compiler error on line 5.
E. Compiler error on line 7.
F. A runtime exception is thrown.
A

A. Line 3 uses local variable type inference to create the map. Lines 5 and 7 use autoboxing to convertbetween the int primitive and the Integer wrapper class. The keys map to their squared value. 1maps to 1, 2 maps to 4, 3 maps to 9, 4 maps to 16, and so on.

25
Q

Which of these statements can fill in the blank so that the Helper class compiles successfully? (Choose all that apply.)

2: public class Helper {
3: public static <u>
4: void printException(U u) {
5:
6: System.out.println(u.getMessage());
7: }
8: public static void main(String[] args) {
9: Helper.\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_;
10: } }</u>

A. printException(new FileNotFoundException("A"))
B. printException(new Exception("B"))
C.  < Throwable > printException(new Exception("C"))
D.  < NullPointerException > printException(new NullPointerException ("D"))
E. printException(new Throwable("E"))</u>
A

A, B, D. The generic type must be Exception or a subclass of Exception since this is an upperbound. Options C and E are wrong because Throwable is a superclass of Exception. Option D usesan odd syntax by explicitly listing the type, but you should be able to recognize it as acceptable.

26
Q

Which of these statements can fill in the blank so that the Wildcard class compiles successfully?(Choose all that apply.)

3: public class Wildcard {
4: public void showSize(List> list) {
5: System.out.println(list.size());
6: }
7: public static void main(String[] args) {
8: Wildcard card = new Wildcard();
9: \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_;
10: card.showSize(list);
11: } }

A. List < ? > list = new HashSet < String > ()
B. ArrayList < ? super Date > list = new ArrayList < Date > ()
C. List < ? > list = new ArrayList < ? > ()
D. List < Exception > list = new LinkedList < java.io.IOException > ()
E. ArrayList < ? extends Number > list = new ArrayList < Integer > ()
F. None of the above

A

B, E. The showSize() method can take any type of List since it uses an unbounded wildcard. OptionA is incorrect because it is a Set and not a List. Option C is incorrect because the wildcard is notallowed to be on the right side of an assignment. Option D is incorrect because the generic types arenot compatible.Option B is correct because a lower-bounded wildcard allows that same type to be the generic. OptionE is correct because Integer is a subclass of Number.

27
Q

What is the result of the following program?

3:  public class Sorted
4:     implements Comparable < Sorted > , Comparator< Sorted > {
5:
6:     private int num;
7:     private String text;
8: 
9:     // Assume getters/setters/constructors provided
10:
11:    public String toString() { return "" + num; }
12:    public int compareTo(Sorted s) {
13:       return text.compareTo(s.text);
14:    }
15:    public int compare(Sorted s1, Sorted s2) {
16:       return s1.num - s2.num;
 17:    }
18:    public static void main(String[] args) {
19:       var s1 = new Sorted(88, "a");
20:       var s2 = new Sorted(55, "b");
21:       var t1 = new TreeSet < Sorted > ();
22:       t1.add(s1); t1.add(s2);
23:       var t2 = new TreeSet < Sorted > (s1);
24:       t2.add(s1); t2.add(s2);
25:       System.out.println(t1 + " " + t2);
26:    } }
A. [55, 88] [55, 88]
B. [55, 88] [88, 55]
C. [88, 55] [55, 88]
D. [88, 55] [88, 55]
E. The code does not compile.
F. A runtime exception is thrown.
A

C. This question is difficult because it defines both Comparable and Comparator on the same object.The t1 object doesn’t specify a Comparator, so it uses the Comparable object’s compareTo() method.This sorts by the text instance variable. The t2 object did specify a Comparator when calling theconstructor, so it uses the compare() method, which sorts by the int.

28
Q

What is the result of the following code? (Choose all that apply.)

Comparator < Integer > c1 = (o1, o2) -> o2 - o1;
Comparator < Integer > c2 = Comparator.naturalOrder();
Comparator < Integer > c3 = Comparator.reverseOrder();
var list = Arrays.asList(5, 4, 7, 2);
Collections.sort(list,\_\_\_\_\_\_\_\_\_\_\_\_\_);
System.out.println(Collections.binarySearch(list, 2));

A. One or more of the comparators can fill in the blank so that the code prints 0.
B. One or more of the comparators can fill in the blank so that the code prints 1.
C. One or more of the comparators can fill in the blank so that the code prints 2.
D. The result is undefined regardless of which comparator is used.
E. A runtime exception is thrown regardless of which comparator is used.
F. The code does not compile.

A

A. When using binarySearch(), the List must be sorted in the same order that the Comparator uses.Since the binarySearch() method does not specify a Comparator explicitly, the default sort order isused. Only c2 uses that sort order and correctly identifies that the value 2 is at index 0. Therefore,option A is correct. The other two comparators sort in descending order. Therefore, the preconditionfor binarySearch() is not met, and the result is undefined for those two.

29
Q

Which of the following statements are true? (Choose all that apply.)

A. Comparable is in the java.util package.
B. Comparator is in the java.util package.
C. compare() is in the Comparable interface.
D. compare() is in the Comparator interface.
E. compare() takes one method parameter.
F. compare() takes two method parameters.

A

B, D, F. The java.lang.Comparable interface is implemented on the object to compare. It specifiesthe compareTo() method, which takes one parameter. The java.util.Comparator interface specifiesthe compare() method, which takes two parameters

30
Q

Which options can fill in the blanks to make this code compile? (Choose all that apply.)

1: public class Generic____________{
2: public static void main(String[] args) {
3: Generic < String > g = new Generic_____________();
4: Generic < Object > g2 = new Generic();
5: }
6: }

A. On line 1, fill in with < > .
B. On line 1, fill in with < T > .
C. On line 1, fill in with < ? > .
D. On line 3, fill in with < > .
E. On line 3, fill in with < T > .
F. On line 3, fill in with < ? > .
A
B, D. 
Line 1 is a generic class that requires specifying a name for the type. Options A and C are incorrect because no type is specified. While you can use the diamond operator < > and the wildcard ?on variables and parameters, you cannot use them in a class declaration. This means option B is the only correct answer for line 1. Knowing this allows you to fill in line 3. Option E is incorrect because T is not a class and certainly not one compatible with String. Option F is incorrect because a wildcard cannot be specified on the right side when instantiating an object. We're left with the diamond operator, making option D correct.
31
Q

Which of the following lines can be inserted to make the code compile? (Choose all that apply.)

  class W {}
  class X extends W {}
  class Y extends X {}
  class Z < Y > {
  // INSERT CODE HERE
  }
A. W w1 = new W();
B. W w2 = new X();
C. W w3 = new Y();
D. Y y1 = new W();
E. Y y2 = new X();
F. Y y1 = new Y();
A
A, B. 
Y is both a class and a type parameter. This means that within the class Z, when we refer to Y, it uses the type parameter. All of the choices that mention class Y are incorrect because it no longer means the class Y.
32
Q

Which options are true of the following code? (Choose all that apply.)

3: _______________ q = new LinkedList<>();
4: q.add(10);
5: q.add(12);
6: q.remove(1);
7: System.out.print(q);

A. If we fill in the blank with List, the output is [10].
B. If we fill in the blank with List, the output is [10, 12].
C. If we fill in the blank with Queue, the output is [10].
D. If we fill in the blank with Queue, the output is [10, 12].
E. The code does not compile in either scenario.
F. A runtime exception is thrown.

A

A, D.
A LinkedList implements both List and Queue. The List interface has a method to remove by index. Since this method exists, Java does not auto box to call the other method. Queue has only the remove by object method, so Java does autobox there. Since the number 1 is not in the list, Java does not remove anything for the Queue.

33
Q

What is the result of the following code?

4: Map m = new HashMap();
5: m.put(123, “456”);
6: m.put(“abc”, “def”);
7: System.out.println(m.contains(“123”));

A. false
B. true
C. Compiler error on line 4
D. Compiler error on line 5
E. Compiler error on line 7
F. A runtime exception is thrown.
A

E.
This question looks like it is about generics, but it’s not. It is trying to see whether you noticed thatMap does not have a contains() method. It has containsKey() and containsValue() instead. IfcontainsKey() was called, the answer would be false because 123 is an Integer key in the Map,rather than a String.

34
Q

What is the result of the following code? (Choose all that apply.)

48: var map = Map.of(1,2, 3, 6);
49: var list = List.copyOf(map.entrySet());
50:
51: List < Integer > one = List.of(8, 16, 2);
52: var copy = List.copyOf(one);
53: var copyOfCopy = List.copyOf(copy);
54: var thirdCopy = new ArrayList < > (copyOfCopy);
55:
56: list.replaceAll(x -> x * 2);
57: one.replaceAll(x -> x * 2);
58: thirdCopy.replaceAll(x -> x * 2);
59:
60: System.out.println(thirdCopy);

A. One line fails to compile.
B. Two lines fail to compile.
C. Three lines fail to compile.
D. The code compiles but throws an exception at runtime.
E. If any lines with compiler errors are removed, the code throws an exception at runtime.
F. If any lines with compiler errors are removed, the code prints [16, 32, 4].
G. The code compiles and prints [16, 32, 4] without any changes.

A

A, E.
The key to this question is keeping track of the types. Line 48 is a Map < Integer, Integer > .Line 49 builds a List out of a Set of Entry objects, giving us List < Entry < Integer, Integer > > .This causes a compile error on line 56 since we can’t multiply an Entry object by two.

Lines 51 through 54 are all of type List < Integer > . The first three are immutable, and the one on line54 is mutable. This means line 57 throws an UnsupportedOperationException since we attempt tomodify the list. Line 58 would work if we could get to it. Since there is one compiler error and one runtime error, options A and E are correct.

35
Q

What code change is needed to make the method compile assuming there is no class named T?

public static T identity(T t) {
return t;
}

A. Add  after the public keyword.
B. Add  after the static keyword.
C. Add  after T.
D. Add > after the public keyword.
E. Add > after the static keyword.
F. No change required. The code already compiles.
A

B.

When using generic types in a method, the generic specification goes before the return type.

36
Q

Which of the answer choices make sense to implement with a lambda? (Choose all that apply.)

A. Comparable interface
B. Comparator interface
C. remove method on a Collection
D. removeAll method on a Collection
E. removeIf method on a Collection
A

B, E.
Both Comparator and Comparable are functional interfaces. However, Comparable is intended to be used on the object being compared, making option B correct. The removeIf() method allows specifying the lambda to check when removing elements, making option E correct. Option C is incorrect because the remove() method takes an instance of an object to look for in the Collection to remove. Option D is incorrect because removeAll() takes a Collection of objects to look for in the Collection to remove.

37
Q

Which of the following compiles and prints out the entire set? (Choose all that apply.)

  Set < ? > set = Set.of("lion", "tiger", "bear");
  var s = Set.copyOf(set);
  s.forEach(\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_);
A. () -> System.out.println(s)
B. s -> System.out.println(s)
C. (s) -> System.out.println(s)
D. System.out.println(s)
E. System::out::println
F. System.out::println
G. None of the above
A

F. The first two lines correctly create a Set and make a copy of it. Option A is incorrect becauseforEach takes a Consumer parameter, which requires one parameter. Options B and C are close. Thesyntax for a lambda is correct. However, s is already defined as a local variable, and therefore thelambda can’t redefine it. Options D and E use incorrect syntax for a method reference. Option F is correct.

38
Q

What is the result of the following?

  var map = new HashMap < Integer, Integer > ();
  map.put(1, 10);
  map.put(2, 20);
  map.put(3, null);
  map.merge(1, 3, (a,b) -> a + b);
  map.merge(3, 3, (a,b) -> a + b);
  System.out.println(map);
A. {1=10, 2=20}
B. {1=10, 2=20, 3=null}
C. {1=10, 2=20, 3=3}
D. {1=13, 2=20}
E. {1=13, 2=20, 3=null}
F. {1=13, 2=20, 3=3}
G. The code does not compile.
H. An exception is thrown.
A

F.
The first call to merge() calls the mapping function and adds the two numbers to get 13. It then updates the map. The second call to merge() sees that the map currently has a null value for that key.It does not call the mapping function but instead replaces it with the new value of 3. Therefore, option F is correct.