Generics and Collections Flashcards

1
Q

Declaring a class with generics

A
public class Crate  {
    private T contents;
    public T emptyCrate() {
         return contents;
    }
}

T can be used throughout the class and when the class is instantiated then the T’s become the class object type you specify

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

How to call a method that uses generics

A

Two ways

methodName(“a string”) //Detects automatically

ClassName.methodName(“a string”) //Explicitly

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

Raw Collections

A

Collections that do not use generics

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

What goes wrong in this code?

class Dragon {}
class Unicorn { }
public class LegacyDragons {
    public static void main(String[] args) {
        List unicorns = new ArrayList();
        unicorns.add(new Unicorn());
        printDragons(unicorns);
     }
    private static void printDragons(List dragons) {
         for (Dragon dragon: dragons) { 
             System.out.println(dragon);
          }
     }
}
A

The List unicorns doesn’t use generics, so when it adds a Unicorn, that’s fine but it sees it as an Object. So basically, it compiles because that’s technically legal to pass to printDragons, but the for loop then tries top cast the Unicorn element to Dragon, which causes a ClassCastException.

It will also give you a compiler warning, but still compile

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

What goes wrong with this code?

public class LegacyAutoboxing {
   public static void main(String[] args) { 
         java.util.List numbers = new java.util.ArrayList();
         numbers.add(5);
         int result = numbers.get(0); 
   }
}
A

When the number 5 is added to the List, it is added just as an Object since there isn’t a type specified by generics. So when you try to store that value in an int, it can’t be unboxed how an Integer usually would be able to.

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

Unbounded Wildcard

A

Specified with a ?

public static void printList(List> list)

This indicates that the List could be of anything.

The difference here between just specifying List without generics, is that when we don’t use generics it will treat the list passed in as List, which could allow the wrong types of elements to be added.

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

Upper-bounded Wildcard

A

Specified with a ? extends className

public static void printList(List extends Number> list)

This means the List can be of Number itself, or any class that is a subclass of Number

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

Lower-bounded Wildcards

A

Specified with a ? super className

public static void printList(List super String> list)

This means that the List can be of String itself, or any class that is a superclass of String

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

Mutability of Lists declared with wildcards

A

With unbounded or upper-bounded, the Lists are immutable, meaning you cannot add anything to them.

With lower-bounded, you can add anything that is the lower-bound specified or a subclass of that lower-bound

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

Collection

A

A group of objects contained in a single object

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

List

A

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
12
Q

Set

A

A collection that does not allow duplicate entries

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

Queue

A

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

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

Map

A

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
15
Q

add()

A

Inserts a new element into the Collection and returns whether it was
successful.

boolean add(E element)

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

remove()

A

Removes a single matching value in the Collection and returns whether it was successful.

boolean remove(Object object)

Removes the element at the specified index

void remove(int index)

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

clear()

A

Discards all elements in the Collection

void clear()

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

contains()

A

Checks if a certain value is in the Collection

boolean contains(Object object)

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

Benefit of ArrayList

A

You can look up any element in constant time.

Adding or removing an element is slower than accessing an element.

This makes an ArrayList a good choice when you are reading more often than writing

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

Benefit of LinkedList

A

You can access, add, and remove from the
beginning and end of the list in constant time.

The tradeoff is that dealing with an arbitrary
index (not necessarily first or last) takes linear time.

This makes a LinkedList a good choice when you’ll be using it as Queue.

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

What should you use instead of Stack?

A

ArrayDeque

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

List method used to add an element at a specific index

A

void add(int index, E element)

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

List method to grab a specific element in the list

A

E get(int index)

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

List method to replace the element at a specific index

A

E set(int index, E e)

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

List method to find the position in the List that matches a specified element

A
//For first match
int indexOf(Object o)
//For the last match
int lastIndexOf(Object o)

Both return -1 if there is no match found

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

Benefit of HashSet

A

Adding elements and checking if an element is in the set are done in constant time

The tradeoff is that you lose the order in which you added the elements, but this is the case with sets usually, so if you care that much then don’t use a set ya dummy.

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

Benefit of TreeSet

A

The set is always in sorted order.

The tradeoff is that adding and checking if an element is present are done in O(logn)

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

TreeSet method

E lower(E e)

A

Returns the greatest element in the set that is

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

TreeSet method

E floor(E e)

A

Returns the greatest element in the set that is <=e, or null if there is no such element

30
Q

TreeSet method

E ceiling(E e)

A

Returns the smallest element in the set that is >=e, or null if there is no such element

31
Q

TreeSet method

E higher(E e)

A

Returns the smallest element in the set that is >e, or null if there is no such element

32
Q

ArrayDeque

A

A double-ended queue that stores its elements in a resizable array

Like a LinkedList, but more efficient

33
Q

ArrayDeque method

boolean add(E e)

A

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

34
Q

ArrayDeque method

E element()

A

Returns next element or throws an exception if empty queue

35
Q

ArrayDeque method

boolean offer(E e)

A

Adds an element to the back of the queue and returns whether successful

36
Q

ArrayDeque method

E remove()

A

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

37
Q

ArrayDeque method

void push(E e)

A

Adds an element to the front of the queue

38
Q

ArrayDeque method

E poll()

A

Removes and returns next element or

returns null if empty queue

39
Q

ArrayDeque method

E peek()

A

Returns next element or returns null if

empty queue

40
Q

ArrayDeque method

E pop()

A

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

41
Q

HashMap

A

Stores keys in a hash table

Adding elements and retrieving the element by key both have constant time.

42
Q

TreeMap

A

Stores keys in a sorted tree structure

Adding and checking if a key is present are both O(log n).

43
Q

What is special about Map in this discussion?

A

It does not extend Collection

44
Q

Map method

void clear()

A

Removes all keys and values from the map.

45
Q

Map method

boolean isEmpty()

A

Returns whether the map is empty.

46
Q

Map method

int size()

A

Returns the number of entries (key/value pairs) in the map.

47
Q

Map method

V get(Object key)

A

Returns the value mapped by key or null if none is mapped.

48
Q

Map method

V put(K key, V value)

A

Adds or replaces key/value pair. Returns previous value or null.

49
Q

Map method

V remove(Object key)

A

Removes and returns value mapped to key. Returns null if none.

50
Q

Map method

boolean containsKey(Object key)

A

Returns whether key is in map.

51
Q

Map method

boolean containsValue(Object)

A

Returns value is in map.

52
Q

Map method

Set keySet()

A

Returns set of all keys.

53
Q

Collection values()

A

Returns Collection of all values.

54
Q

Which of the data structures discussed cannot contain null elements?

A

TreeSet cannot contain null elements

TreeMap cannot contain null keys, but CAN contain null values

ArrayDeque cannot contain null elements

55
Q

Comparable interface

A

public interface Comparable {
public int compareTo(T o);
}

Only contains the compareTo() method

56
Q

compareTo() rules

A

The number zero is returned when the current object is equal to the argument to compareTo().

A number less than zero is returned when the current object is smaller than the argument to compareTo().

A number greater than zero is returned when the current object is larger than the argument to compareTo().

57
Q

Comparator

A

A functional interface that you can use to sort a collection of objects by however you specify its compare() function.

You can define it in long form, (for example):

Comparator byWeight = new Comparator() {
     public int compare(Duck d1, Duck d2) { 
          return d1.getWeight()—d2.getWeight();
     }
};

Or as a lambda:

Comparator byWeight = (d1, d2) -> d1.getWeight()—d2.getWeight();

58
Q

How to use a comparator to sort

A

Collections.sort(listname, byWeight);

59
Q

What package is Comparable in? Comparator?

A

Comparable is in java.lang

Comparator is in java.util

60
Q

What is the method in Comparable? Comparator?

A

Comparable has compareTo(T obj)

Comparator has compare(T obj1, T obj2))

61
Q

Method References

A

A way to make the code shorter by reducing some of the code that can be inferred and simply mentioning the name of the method.

62
Q

How can you shorten the following line of code using a method reference?

Comparator byWeight = (d1, d2) -> DuckHelper.compareByWeight(d1, d2);

A

Comparator byWeight = DuckHelper::compareByWeight;

63
Q

How can you shorten the following line of code using a method reference?

String str = “abc”;
Predicate lambda2 = s -> str.startsWith(s);

A

Predicate methodRef2 = str::startsWith;

64
Q

How can you shorten the following line of code using a method reference?

Predicate lambda3 = s -> s.isEmpty();

A

Predicate methodRef3 = String::isEmpty;

65
Q

How can you shorten the following line of code using a method reference?

Supplier lambda4 = () -> new ArrayList();

A

Supplier methodRef4 = ArrayList::new;

66
Q

How to use

boolean removeIf(Predicate super E> filter)

A

If we have a List of Strings, an example is

list.removeIf(s -> s.startsWith(“A”));

67
Q

How to use

void replaceAll(UnaryOperator o)

A

List list = Arrays.asList(1, 2, 3);
list.replaceAll(x -> x*2);
System.out.println(list); // [2, 4, 6]

Note: The lambda may only take one argument because it is a UnaryOperator

68
Q

How to loop through a Collection using a lambda or method reference

A

list. forEach(c -> System.out.println(c));

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

69
Q

How to insert a new key/value pair into a Map

A

Map mymap = new HashMap<>();
mymap.put(“My key”, “My value”);

Note: you can use putIfAbsent() if you want to make sure you don’t overwrite a value that is already in the map

70
Q

merge()

Full Version:
merge(K key, V value, BiFunction super V,? super V,? extends V> remappingFunction)

A

Uses the BiFunction to make a decision on changing a the value for the specified key

Returns the result of the BiFunction

71
Q

What happens if you call merge() on a key with a null value or a key that doesn’t exist?

A

It doesn’t call the BiFunction (this would cause a NullPointerException) and it just inserts the new value in question

72
Q

What happens if you call merge() on a key and the BiFunction is called and returns null?

A

The key is removed from the map