Chapter 14: 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

Which functional interface takes two parameters and returns a boolean?

A

BiPredicate

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
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
6
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
7
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
8
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
9
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
10
Q

How do you convert a float to its wrapper class Float?

A

using Float.valueOf();

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

What will this code produce?

var heights = new ArrayList();
heights.add(null);
int h = heights.get(0);
System.out.println(h);
A

It will throw a NullPointerException when trying to assign a null value to a primitive.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
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
13
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
14
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
15
Q

What is the generic type of the following statement?

var list = new ArrayList<>();

A

Object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
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
17
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
18
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
19
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
20
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
21
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
22
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
23
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
24
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

(More on this in chapter 18).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
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
26
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
27
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
28
Q

When do you want to use a List?

A

When you want an ordered list that can contain duplicate entries.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
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
30
Q

What data structure is best if you are reading more often than (or the same amount as) writing?

A

ArrayList

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

What is the main benefit of using an ArrayList?

A
  • You can access, add and remove from the beginning and end of the list in constant time.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
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
33
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
34
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
35
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
36
Q

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

A

Yes.

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

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

A

No.

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

What is the result of the following code?

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

System.out.println(asList);

A

[c, b]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
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
40
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
41
Q

What is the result of the following code?

List asList = Arrays.asList();
asList.set(0, “x”);

System.out.println(asList);

A

It throws a IndexOutOfBoundsException.

Because there are no elements in the list, there are no elements to replace.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
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.replace(x -> x * 2);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
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
44
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
45
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
46
Q

What is the disadvantage of a Set?

A

You lose the order in which you inserted the elements.

47
Q

What is the main benefit of a TreeSet?

A

It is always in sorted order.

48
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.

49
Q

What factory methods exist to create a Set?

A
  • Set.of(varargs) // immutable

- Set.copyOf(Set) //immutable

50
Q

What does the second add method return?

Set set = new HashSet<>();

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

A

False.

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

52
Q

When do you want to use a queue?

A

When elements are added and removed in a specific order.

53
Q

What does deque stand for?

A

Double-ended queue

54
Q

Which Queue implementation is more efficient than a LinkedList?

A

ArrayDeque

55
Q

What does the queue method element() do?

A

Returns next element or throws an exception if empty queue.

56
Q

What does the queue method offer() do?

A

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

57
Q

What does the queue method remove() do?

A

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

58
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.

59
Q

What does the queue method poll() do?

A

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

60
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.

61
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.

62
Q

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

A

boolean containsKey(Object key)

63
Q

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

A

boolean containsValue(Object key)

64
Q

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

A

Set> entrySet();

65
Q

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

A

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

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

67
Q

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

A

Set keySet()

68
Q

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

A

V putIfAbsent(K key, V value)

69
Q

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

A

Collection values()

70
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.

71
Q

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

A

get()

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

73
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.

74
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).

75
Q

Which data structures does not allow null values?

A

TreeMap and TreeSet

76
Q

How much null values does Set allow?

A

One.

Any more count as duplicates.

77
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.

78
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.

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

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

81
Q

Why should Comparable classes be consistent with equals?

A

Because not all collection classes behave predictably if the compareTo() and equals() methods are not consistent.

82
Q

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

A

Using the Comparator interface

83
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.

84
Q

What package does Comparable reside in?

A

java.lang

85
Q

What package does Comparator reside in?

A

java.util

86
Q

What abstract method name does Comparator define?

A

compare()

87
Q

What abstract method name does Comparable define?

A

compareTo()

88
Q

How many parameters does compare() take?

A

2

89
Q

How many parameters does compareTo() take?

A

1

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

91
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.

92
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.

93
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.

94
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.

95
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.

96
Q

Given an interface Shippable with a generic type T and an abstract method ship(T t), how do we implement it in a concrete class as a raw type?

A

class .. implements Shippable {
… ship(Object t) { }
}

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

98
Q

is the following statement valid?

public static T hello(T t) {}

A

No, because it is missing a formal parameter type.

correct:

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

99
Q

is the following statement valid?

public static void hello(T t) {}

A

Yes.

100
Q

Given the following code, what is the type returned in the method tricky()?

public class Crate< E> {
    public < T> T tricky (T t) {
        return t;
    }
}
// ...
public static String createName() {
    Crate crate = new Crate< Object>();
    return crate.tricky("bot");
}
A

The type returned is a String.

When you have a method declare a generic parameter type, it is independent of the class generics.

101
Q

What is an unbounded wildcard?

A

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

List< ?> a = new ArrayList();

102
Q

Why should List> be used over List for using a generic list?

A

You cannot assign a List of a specific type to a List (or anything else), even if it inherits from Object.

103
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
104
Q

Is the following statement valid?

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

A

No. A generic type cannot use a subclass.

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

106
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.

107
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 a of a certain type or a superclass of that type.

example: List < ? super String>

108
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.

109
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.

110
Q

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

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

  1. List< A> list1 = new ArrayList<a>();</a>
  2. List < ? extends B> list2 = new ArrayList</a><a>();</a>
  3. List < ? super A> list3 = new ArrayList();
  4. List> list4 = new ArrayList< ? extends A>();
  5. List < ? super B> list5 = new ArrayList();</a>
A
  1. compiles
  2. does not compile
  3. compiles
  4. does not compile
  5. compiles

(page 654)

111
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.

112
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.

(page 655)

113
Q

void fifth(List< extends Number> list) { }

A

A wildcard must have a ? in it.

page 655