Ch14 Generics and Collections Flashcards

1
Q

What is a method reference?

A

An operation that looks like this:

System.out::println;

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

Given the following statement, write an equivalent statement using method reference.

Consumer> lambda = x -> Collections.sort(x);

A

Consumer> methodRef = Collections::sort;

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

Given the following lamda expression, write an equivalent method reference.

var str = “abc”;
s -> str.startsWith(s);

A

var str = “abc”;
str::startsWith;

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

What is a constructor reference?

A

A constructor reference is a special type of method reference that uses new instead of a method, and it instantiates an object. It is common to use a Supplier.

example
Supplier> methodRef = ArrayList::new;

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

Which functional interface takes one parameter and returns a result? (not a boolean).

A

Function

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

How do you convert a boolean to its wrapper class Boolean?

A

using Boolean.valueOf();

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

How do you convert a byte with variable name x to its wrapper class Byte?

A

using Byte.valueOf((byte)x);

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

How do you convert a short with variable name x to its wrapper class Short?

A

using Short.valueOf((short)x);

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

What does the following code output?

List numbers = new ArrayList<>();
numbers.add(1);
numbers.add(Integer.valueOf(3));
numbers.add(Integer.valueOf(5));
numbers.remove(1);
numbers.remove(Integer.valueOf(5));
System.out.println(numbers);

A

It prints [1] because the remove() method is overloaded.

The first remove() call removes the object at index 1.
The second remove() call removes the object that should be removed.

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

How can we use the diamond operator to make the following code shorter?

List numbers = new ArrayList();

A

List numbers = new ArrayList<>();

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

How can we use the diamond operator to make the following code shorter?

List< Object> numbers = new ArrayList< Object>();

A

List< Object> numbers = new ArrayList<>();

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

What are the four main interfaces in the Java Collections Framework?

A
  • List
  • Set
  • Queue
  • Map
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is a List?

A

A list is an ordered collection of elements that allows duplicate entries. Elements in a list can be accessed by an int index.

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

What is a Set?

A

A set is a collection that does not allow duplicate entries.

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

What is a Queue?

A

A queue is a collection that orders its elements in a specific order for processing. A typical queue processes its elements in a first-in, first-out orderm but other orderings are possible.

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

What is a Map?

A

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs.

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

What interfaces/data structures extend the Collection interface? And which one does not?

A

Interfaces that extend Collection:

  • List
  • Queue
  • Set

Interface that does not extend Collection:
* Map

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

How do we insert a new element into a Collection and what does it return?

A

Using the add() method.

It returns true, if the operation was succesful.

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

How do we remove a new element into a Collection and what does it return?

A

Using the remove() method.

It returns true, if the operation was succesful.

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

Is the following code valid?

Collection birds = new ArrayList<>();

birds. add(“hawk”);
birds. add(“hawk”);
birds. add(“hawk”);

for (String bird : birds) {
birds.remove(bird);
}

A

No. Java does not allow removing elements from a list while using the enhanced for loop.

It will throw a ConcurrentModificationException

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

How do we discard all elements of a Collection?

A

using the clear() method.

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

How do we remove an element using a condition?

A

With the removeIf() method, which takes a Predicate and returns true/false.

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

How do we loop through a Collection (without using a for/while loop)?

A

Using the method forEach() which takes a Consumer.

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

What is the main benefit of using an ArrayList?

A
  • It resizes automatically
  • You can look up any element in constant time.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What data structure is best if you want to use one as a queue?

A

Linkedlist

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

What factory methods exist to create a List?

A
  • Arrays.asList(varags)
  • List.of(varargs)
  • List.copyOf(collection)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Which factory methods for creating a list return an immutable list?

A
  • List.of(varargs)
  • List.copyOf(collection)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Is it possible to add an element to a list created by Arrays.asList(varargs)?

A

No.

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

What is the result of the following code?

String[] array = new String[] {“a”, “b”};
List asList = Arrays.asList(array);

asList.set(0, “x”);

System.out.println(Arrays.toString(array));

A

[x, b]

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

What is the result of the following code?

String[] array = new String[] {“a”, “b”};
List asList = Arrays.asList(array);

asList.add(0, “x”);

System.out.println(asList);

A

This code throws an UnsupportedOperationException because Arrays.asList returns a fixed sized list.

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

Given the following list, what List method can we use to multiply all numbers by 2?

List numbers = Arrays.asList(1, 2, 3);

A

numbers.replaceAll(x -> x * 2);

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

What (often-used) implementations of Set exist?

A
  • HashSet
  • TreeSet
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

How does a HashSet store elements?

A

A HashSet stores its elements in a hash table, which means the keys are a hash and the values are an Object. This means that it uses the hashCode() method of the objects to retrieve them more efficiently.

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

What is the main benefit of a Set?

A

Adding elements and checking wether an element is in the set both have constant time.

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

What is the disadvantage of a Set?

A

You lose the order in which you inserted the elements.

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

What is the main benefit of a TreeSet?

A

It is always in sorted order.

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

What is the disadvantage of a TreeSet?

A

Adding and checking wether an element exists takes longer than with a HashSet, especially as the tree grows larger.

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

What factory methods exist to create a Set?

A
  • Set.of(varargs) // immutable
  • Set.copyOf(Set) //immutable
39
Q

What does the second add method return?

Set set = new HashSet<>();

set. add(66);
set. add(66);

A

False.

40
Q

What does the print statement print?

Set set = new TreeSet<>();

set. add(66);
set. add(8);
set. add(10);

set.forEach(System.out::println);

A

8
10
66

(retains natural order)

41
Q

When do you want to use a queue?

A

When elements are added and removed in a specific order.

42
Q

Which Queue implementation is more efficient than a LinkedList?

A

ArrayDeque

43
Q

What does the queue method element() do?

A

Returns next element or throws an exception if empty queue.

44
Q

What does the queue method offer() do?

A

Adds an element to the back of the queue and returns wether succesful (boolean).

45
Q

What does the queue method remove() do?

A

Removes and returns next element or throws an exception if empty queue.

46
Q

What does the queue method add() do?

A

Adds an element to the back of the queue and returns true or throws an exception.

47
Q

What does the queue method poll() do?

A

Removes and returns next element or returns null if empty queue.

48
Q

What does the queue method peek() do?

A

Returns next element or returns null if empty queue. Does not remove the element from the queue.

49
Q

When do you want to use a Map?

A

When you want to identify values by a key. For example, when you use the contact list in your phone, you look up “George” rather than looking through ech phone number in turn.

50
Q

What Map interface method can we use to check if a key is inside a Map?

A

boolean containsKey(Object key)

51
Q

What Map interface method can we use to check if a value is inside a Map?

A

boolean containsValue(Object key)

52
Q

What Map interface method can we use to return a Set of key/value pairs?

A

Set> entrySet();

53
Q

What Map interface method can we use to loop through each key/value pair?

A

void forEach(BiConsumer(K key, V value))

54
Q

What Map interface method can we use to get a value, and if not exists, return a default value?

A

V getOrDefault(Object key, V defaultValue);

55
Q

What Map interface method can we use to get a Set of all keys?

A

Set keySet()

56
Q

What Map interface method can we use to add a value if key is not present?

A

V putIfAbsent(K key, V value)

57
Q

What Map interface method can we use to get a Collection of all values?

A

Collection values()

58
Q

What does the following code do?

Map map = new HashMap<>();
map.put(“koala”, “bamboo”);

System.out.println(map.contains(“koala”));

A

It will not compile because Map doesn’t have a contains method (Collection does!).

Map does have a containsKey() and containsValue() method.

59
Q

What method do we use for a Map object to get a value and return null if not present?

A

get()

60
Q

What method do we use for a Map object to update a value based on the condition of a function?

A

merge(K key, V value, Function( func))

61
Q

What is the result of the following code?

BiFunction mapper = (v1, v2) -> null;
Map favorites = new HashMap<>();

favorites. put(“Jenny”, “Bus Tour”);
favorites. put(“Tom”, “Bus Tour”);
favorites. merge(“Jenny”, “Skyride”, mapper);
favorites. merge(“Sam”, “Skyride”, mapper);

System.out.println(favorites);

A

{Tom=Bus Tour, Sam=Skyride}

Because the function returns null, existing keys will be removed. Therefore, Jenny was removed.

Sam was added because it was not present in the HashMap.

62
Q

What is the result of the following code?

BiFunction mapper = (v1, v2) -> v1.length() > v2.length ? v1 : v2;
Map favorites = new HashMap<>();
favorites.put(“Jenny”, null);
favorites.merge(“Jenny”, “Skyride”, mapper);

System.out.println(favorites);

A

{Jenny=Skyride}

If the value of a key is null and merge() is called on it, it will be updated. The mapper will not be called (which would produce a NullPointerException).

63
Q

Which data structures does not allow null keys or null values?

A
  • TreeMap does not allow - Null Key
  • TreeSet does not allow - Null Element
64
Q

Given the following characters: A, 8, b, when sorting a String, what is the result when sorting the characters?

A
  1. 8
  2. b
  3. A
    numbers before letters.
    lowercase before uppercase letters.
65
Q

How do we use Collections.sort() (without parameters) on an object that we create ourself such that it sorts the object without issues?

A

By implementing the Comparable interface.

66
Q

Given the following code, how do we implement the compareTo method to be able to sort on name (ascending)?

public class Duck implements Comparable {
private String name;
// …
public int compareTo(Duck d) {
// code here
}
}

A

return name.compareTo(d.name);

67
Q

Given the following code, how do we implement the compareTo method to be able to sort on id (descending)?

public class Duck implements Comparable {
private int id;
// …
public int compareTo(Duck d) {
// code here
}
}

A

return d.id - id;

68
Q

How can we apply custom sorting without using the Comparable interface?

A

Using the Comparator interface

69
Q

When do you want to use a Comparator vs a Comparable?

A

A Comparator should be used when you want to sort objects in different ways at different times.

A Comparable should be used when you want to sort objects in one specific way.

70
Q

What package does Comparable reside in?

A

java.lang

71
Q

What package does Comparator reside in?

A

java.util

72
Q

What abstract method name does Comparator define?

A

compare()

73
Q

What abstract method name does Comparable define?

A

compareTo()

74
Q

Given a Squirrel class with a getName() method, how do we sort it in descending order using Comparator static helper methods?

A

Comparator.comparing(Squirrel::getName).reversed();

75
Q

Is the following code valid?

public class SortRabbits {
static class Rabbit { int id; }
public static void main(String[] args) {
List rabbits = new ArrayList<>();
rabbits.add(new Rabbit());
Collections.sort(rabbits);
}
}

A

It does not compile because Java knows that the Rabbit class is not Comparable.

76
Q

Is the following code valid?

public class SortRabbits {

static class Rabbit { int id; }

public static void main(String[] args) {
List rabbits = new ArrayList<>();
rabbits.add(new Rabbit());
Comparator c = (r1, r2) -> r1.id - r2.id;
Collections.sort(rabbits, c);
} }

A

This code is valid.

Collections.sort can take in a Comparator object when you don’t want to use natural order.

77
Q

Is the following code valid?

// …
static class Rabbit { int id; }
Set rabbits = new TreeSet<>();
rabbits.add(new Rabbit());
// …

A

It is invalid because TreeSet is not able to sort it and then throws a ClassCastException.

To fix this, Rabbit needs to implement Comparable.

78
Q

Is the following code valid?

// …
static class Rabbit { int id; }
Set rabbits = new TreeSet<>((r1, r2) -> r1.id - r2.id);
rabbits.add(new Rabbit());
// …

A

This is valid. You can pass a Comparator to a TreeSet to let Java know how you want to sort the Objects.

79
Q

What is type erasure?

A

Type erasure is the process of removing the generic syntax from your code, which allows your code to be compatible with older versions of Java that do not contain generics.

80
Q

How do you write a public generic method that take a generic parameter and returns a generic object?

A

public <T> T returnObject(T t) {
return t;
}

81
Q

is the following statement valid?

public class Lol {
public static T hello(T t) {}
}

A

No, because it is missing a formal parameter type.

correct:

public static <T> T hello(T t) {}

82
Q

What is an unbounded wildcard?

A

An unbouded wildcard represents any data type and uses the syntax ‘?’.

List< ?> a = new ArrayList();

83
Q

Are these statements equal?

List< Object> x1 = new ArrayList<>();
var x2 = new ArrayList<>();

A

No.

  • x1 is of type List, x2 is of type ArrayList.
  • x2 can only be assigned to List
84
Q

Is the following statement valid?

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

A

No. A generic type cannot use a subclass.

85
Q

How do we use an Upper-Bounded wildcard to fix the following code?

List list = new ArrayList< Number>();

A

List< ? extends Number> list = new ArrayList< Number>();

86
Q

Does the following code compile?

List< ? extends Bird> birds = new ArrayList();

birds. add(new Sparrow());
birds. add(new Bird());

A

It does not because when working with upper bounds or unbounded wildcards, the list becomes immutable. This is because Java does not know what type List< ? extends Bird> really is.

87
Q

What is a lower bound wildercard and how does it look like?

A

With lowerbound we tell Java the generic type has to be of a certain type or a superclass of that type.

example: List < ? super String>

88
Q

Why does the following code not work?

public static void addSound(List< ? extends Object> list) {
list.add(“quack”);
}

A

User upper-bounded wildcards will result in an immutable list.

89
Q

Why does the following code not work?

public static void addSound(List list) {
list.add(“quack”);
}

A

With generics, you must pass an exact match. String does not match Object.

90
Q

Given the following code, which of these statements compile and which don’t?

Class A {}
Class B extends A {}
Class C extends B {}

List< A> list1 = new ArrayList< A>();
List < ? extends B> list2 = new ArrayList< A>();
List < ? super A> list3 = new ArrayList();
List> list4 = new ArrayList< ? extends A>();
List < ? super B> list5 = new ArrayList();

A
  1. compiles
  2. does not compile
  3. compiles
  4. does not compile
  5. compiles
91
Q

Does the following code compile?

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

A

The return type isn’t actually a type.

92
Q

Why does the following code not compile?

< B> B third(List< B> list) {
return new B();
}

A

B is referred as a type parameter but also happens to be a class name (return new B()). Because B is seen as a type parameter, it cant be instantiated in the return statement.

93
Q

Which of the following statements are correct?

A. A List stores elements in a sorted order.
B. A Set keeps the elements sorted and a List keeps the elements in the order they were added.
C. A SortedSet keeps the elements in the order they were added.
D. An OrderedSet keeps the elements sorted.
E. An OrderedList keeps the elements ordered.
F. A NavigableSet keeps the elements sorted.

A

A NavigableSet is a SortedSet extended with navigation methods reporting closest matches for given search targets. Methods lower, floor, ceiling, and higher return elements respectively less than, less than or equal, greater than or equal, and greater than a given element, returning null if there is no such element. Since NavigableSet is a SortedSet, it keeps the elements sorted.

Answer = F