6. Generics and Collections Flashcards

1
Q

Which of the collection classes are thread safe?

A

Vector and hashtable are thread safe

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

What has to be unique in a map?

A

All keys in a map must be unique. The values can be the same

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

What does the values() return?

A

The values() method returns a collection

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

What does Arrays,binarySearch() return?

A

This method returns the index of the search key, if it is in the list

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

With map supports adding null key as wel as null values?

A

Hashmap

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

equals() and hashCode() methods

A

Whenever you need to sort or search through a collection of objects, the equals() and hashCode() methods are essential. When you really need to know if two references are identical, use ==. But when you need to know if the objects themselves are equal, use the equals() method.

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

What happens when a object does not past the instanceOf test?

A

First, when overriding the equals() method, be sure that the object being tested is of the correct type! It comes in as type Object, so do a instanceof test. Remember, if the object doesn’t pass the instanceof test, you will get a runtime ClassCastException.

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

rules for overriding equals()

A
  • Reflexive: for any reference value x, x.equals(x) should return true
  • Symmetric: x.equals(y) should return true if and only if y.equals(x) return true
  • Transitive: if x.equals(y) return true and y.equals(z) return true, then x.equals(z) must return
    true
  • Consistent: multiple invocations of x.equals(y) consistenly return true or consistently return
    false
  • for any non-null reference value x, x.equals(null) should return false.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Hashcode() contract

A
  • Whenever it is invoked on the same object more than once during an execution of a java
    application, the hashCode() method must consistently return the same integer, provided that
    no information used in equals comparisons on the object is modified
  • If two objects are equal according to the equals(Object) method, then calling hashCode()
    method on each of the two objects must produce the same integer result
  • It is not required that if two objects are unequal according ti the equals(Object) method,
    then callin the hashCode() method on each of the two objects must produce distinct integer
    result
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Wich 14 concrete Collection implementation classes you need to know for the exam?

A

HashMap HashSet ArrayList PriorityQueue Collections
Hashtable LinkedHashSet Vector ArrayDeque Arrays
TreeMap TreeSet LinkedList
LinkedHashMap

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

Which four basic flavours do Collections come in?

A
  • Lists: Lists of things (classes that implement List)
  • Sets: Unique things (classes that implement Set)
  • Maps: Things with a unique ID (classes that implement Map)
  • Queues: Things arranged in the order in which they are to be processed.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

which four sub flavours do Collections come in?

A

Sorted, Unsorted, Ordered,

Unordered.

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

What does Ordered mean?

A

When a collection is ordered, it means you can iterate through the collection in a specific
(not random) order. A Hashtable is not ordered. ArrayList, keeps the order established by the
elements index position. LinkedHashSet keeps the order established by insertion, so the last element inserted is the last element in the LinkedHashSet.

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

What does Sorted mean?

A

sorted means that the order in the collection is determined according to some rule or rules,
known as the “sort order”. Sorting is done based on properties of the objects themselves

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

What is the List interface?

A

A List cares about the index. The one thing that List has that nonlists don’t is a set of methods related to the index (get(int index), indexOf(Object o), add(int index, Object o)). The three list
implementations:

  • ArrayList: think of this as a growable array. It is an ordered collection (by index) but not
    sorted. ArrayList implements the RandomAccess interface (marker interface that says: this
    list support fast random access).
  • Vector: A Vector is basically the same as an ArrayList, but Vector methods are synchronized
    for thread safety. Of the classes discussed here, only Vector and ArrayList implement
    RandomAccess
  • LinkedList: ordered by index postion, except that the elements are doubly linked to one
    another. This linkage gives you new methods, for adding and removing from the beginning or
    end. LinkedList may iterate more slowly than an ArrayList, but its a good choice when you
    need fast insertion and deletion.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the Set interface?

A

A set cares about uniqueness, it doesn’t allow duplicates. The equals() method determines whether two objects are indentical (in which case, only one can be in the set). The three set implementations:

  • HashSet: a HashSet is an unsorted, unordered Set. It uses the hashcode of the object being
    inserted, so the more efficient your hashCode() implementation, the better access
    performance you will get. Use this class when you want a collection with no duplicates and
    you don’t care about order when you iterate through it
  • LinkedHashSet: A LinkedHashSet is an ordered version of HashSet that maintains a doubly
    linked List across all elements. A LinkedHashSet lets you iterate through elements in the
    order in which they were inserted.
  • TreeSet: The treeset is one of two sorted collection (otherone: treemap). It guarantees that
    the element will be in ascending order, according to natural order. Optionally you can
    construct a TreeSet with a constructor that lets you give the collection your own rules for
    what the order should be by using a Comparator.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What do you need to when using HashSet or LinkedHashSet?

A

When using HashSet or LinkedHashSet, the objects you add to them must override
hashCode(). If they don’t override hashCode(), the default hashcode method will allow multiple
objects that you might consider “meaningfully equal” to be added to your “no duplicates allowed” set.

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

What is the Map interface?

A

A map cares about unique identifiers. You map a unique key (the ID) to a specific value, where both the key and the value are objects. The map implementations let you do things like search for a value based on the key, ask for a collection of just the values. Maps rely on the equals() method to determine whether two keys are the same or different.

  • HashMap: The hashMap gives you an unsorted, unordered Map. When you need a Map and
    you don’t care about the order when you iterate through it, then HashMap is the way to go.
    Where the keys land in the Map is based on the key’s hashcode, so like HashSet. HashMap
    allows one null key and multiple null values in a collection.
  • Hashtable: Hashtable is the synchronized counterpart to HashMap. We just mean that the
    key methods of the class are synchronized. And a Hashtable doesn’t let you have anything
    that’s null
  • LinkedHashMap: Like its Set (LinkedHashSet) counterpart. it will be somewhat slower than
    hashMap for adding and removing elements, you can expect faster iteration with a
    LinkedHashMap.
  • TreeMap: TreeMap is a sorted Map – sorted by the natural order of the elements. Via a
    Comparator you can define a custom sort order.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the Queue interface?

A

A Queue is designed to hold a list of “to-dos”, or things to be processed in some way. Although other orders are possible, queues are typically thought of as FIFO. Queues support all of the standard Collection methods and they also have methods to add and subtract elements and review queue elements.

  • PriorityQueue: The purpose is to create a priority-in, priority-out queue as opposed to a
    typical FIFO queue, the elements are ordered either by natural ordering (in which case the
    elements that are sorted first will be accessed first) or according to a Comparator. In either
    case, the elemnts’ ordering represent their relative priority.
  • ArrayDeque: It is a double ended queue, meaning you can add and remove items from both
    ends of the queue. It is a good choice for implementing either a queue or a stack because it is
    resizable with no capacity restriction and it is designed to be high performance (but not
    thread safe)
20
Q

What happens when you don’t specify the object type of an arrayList?

A

If you don’t specify the object type of an ArrayList, it will be an generic ArrayList where you can put anything in.

21
Q

How can you sort objects in your list?

A
If you want to sort the objects in your list with Collections.sort(List list), the objects in the List
must implement the Comparable interface. The String class does implement the Comparable
interface, and thats why we were able to sort a list of String using the sort() method.
22
Q

What is the comparable interface?

A

The Comparable interface is used by the Collections.sort() and the Arrays.sort() to sort Lists and arrays of objects. To implement Comparable, a class must implement a single method, compareTo():

23
Q

What does the compareTo() method returns?

A

The compareTo() method returns an int with the following characteristics:

  • Negative (-1) : If thisObject < anotherObject
  • Zero (0): if thisObject == anotherObject
  • Positive (1): if thisObject > anotherObject
24
Q

ExamWatch!

A

Its important to remember that when you override equals(), you must take an argument of type Object, but that when you override compareTo() you should take an argument of the type you’re sorting.

25
Q

What does the Comparator.compare() returns?

A

The Comparator.compare() returns an int whose meaning is the same as the compareTo() return value.

26
Q

How can you sort an ArrayList?

A

ArrayList can also be sorted directly by calling the sort() method on the list. The ArrayList sort() method takes a Comparator, so we can pass in an instance of a class that implements Comparator, or we can use a lambda expression, just like the Collections.sort().

27
Q

What do you need to remember?

A

Finally, remember that the sort() methods for both the Collections class and the Arrays class are static methods, and that they alter the objects they are sorting instead of returning a different sorted object.

28
Q

Do the elements inside a collection be mutually comparable?

A

whenever you want to sort an array or a collection, the elements inside must all be mutually comparable. In other words, if you have an Object[] and you put Cat and Dog objects into it, you won’t be able to sort it.

29
Q

What does the binarySearch() method do?

A
  • Searches are performed using the binarySearch() method
  • Successful searches return the int index of the element being searched
  • Unsuccessful searches return an int index that represent the insertion point (indicated with
    negative numbers). The insertion point is the place in the collection/array where the element
    would be inserted to keep the collection/array properly sorted.
    o Formule: (-(insertion point) -1)
    o For example: if the insertion point of a search is at element 2, the actual insertion
    point returned will be -3
  • The collection/array being searched must be sorted before you can search it
  • If you attempt to search an array or collection that has not already been sorted, the results
    of the search will not be predictable.
  • If the collection/array you want to search was sorted in natural order, it must be searched in
    natural order
  • If the collection/array you want to search was sorted using a comparator, it must be
    searched using the same Comparator (if you don’t do this, you will get an undefined
    incorrect answer), which is passed as the third argument to the binarySearch(). Remember
    that Comparators cannot be used when searching arrays of primitives.
30
Q

How to convert arrays to lists and lists to arrays?

A

A couple of methods allow you to convert arrays to Lists and Lists to arrays. The List and Set classes have toArray() methods, and the Arrays class has method called asList(). The asList() copies an array into a list. When you update one of them the other is updated automatically. The toArray() method comes in two flavors: one that returns a new Object array, and one that uses the array you send it as the destination array.

31
Q

Which two Iterator methods you need to understand?

A

Two Iterator methods you need to understand for the exam are:

  • Boolean hasNext(): returns true if there is at least one more element in the collection being traversed.
  • Object next(): this method returns the next object in the collection and moves you forward to the element after the element just returned.
    You make an Iterator as follow: Iterator iterate = obj.iterator(); If you don’t use the generic syntax you had to cast the returned value.
32
Q

What does the Set.add() method return?

A

If you attempt to add an element to a set that already exists in the set, the duplicate element will not be added, and the add() method will return false. You must use caution when using a TreeSet. HashSets do not guarantee any ordering, so the order of objects printed in the second for loop is not predictable.

You can put only elements in a TreeSet that can be mutually comparable, otherwise you’ll get a classCastException.

33
Q

What does TreeSet.ceiling(e) and TreeMap.ceilingKey(key) do?

A
  • TreeSet.ceiling(e)
    Returns the lowest element >= e
  • TreeMap.ceilingKey(key)
    Returns the lowest key >= key
34
Q

What does TreeSet.higher(e) and TreeMap.higherKey(key) do?

A
  • TreeSet.higher(e)
    Returns the lowest element > e
  • TreeMap.ceilingKey(key)
    Returns the lowest key > key
35
Q

What does TreeSet.floor(e) and TreeMap.floorKey(key) do?

A
  • TreeSet.floor(e)
    Returns the lowest element <= e
  • TreeMap.floorKey(key)
    Returns the lowest key <= key
36
Q

What does TreeSet.lower(e) and TreeMap.lowerKey(key) do?

A
  • TreeSet.floor(e)
    Returns the lowest element < e
  • TreeMap.floorKey(key)
    Returns the lowest key < key
37
Q

What does TreeSet.pollFirst() and TreeMap.pollFirstEntry() do?

A
  • TreeSet.pollFirst()
    Returns and removes the first entry

-TreeMap.pollFirstEntry()
Returns and removes the first key/value pair

38
Q

What does TreeSet.pollLast() and TreeMap.pollLastEntry() do?

A
  • TreeSet.pollLast()
    Returns and removes the last entry

-TreeMap.pollLastEntry()
Returns and removes the last key/value pair

39
Q

What does TreeSet.descendingSet() and TreeMap.descendingMap() do?

A
  • TreeSet.descendingSet()
    Returns a NavigableSet in reverse order

-TreeMap.DescendingMap()
Returns a NavigableMap in reverse order

40
Q

What does subMap() method do?

A
The subMap() method is making a copy of a portion of the TreeMap
named map. When we add key/value pairs to either the original TreeMap or the partial-copy SortedMap, the new entries were automatically added to the other collection. When submap was created we provided a value range for the new collection. This range defines not only what should be included when the partial copy is created, but also defines the range of values that can be added to the copy.
41
Q

What are the Backed Collection methods for TreeSet and TreeMap?

A

HeadSet(e, b*) - returns a subset ending at element e and exclusive of e

headMap(k, b*) - returns a submap ending at element k and exclusive of k

tailSet(e, b*) - returns a subset starting at element e and exclusive of e

tailMap(k, b*) - returns a submap starting at element k and exclusive of k

subSet(s, b, e, b) Returns a subset starting at element s and ending just before element e

subMap(s, b, e, b) Returns a submap starting at key s and ending just before key e

  • = optional boolean, lets you specify wether the start/ end point are exclusive.

All these methods return a Navigable

42
Q

What is a PriorityQueue?

A

Unlike basic queue that are FIFO by default, a PriorityQueue orders its elements using a user-defined priority. The priority can be as simple as natural ordering, it can be ordered using a Comparator.

With the offer() method you can add elements to the PriorityQueue. The poll() returns the highest-priority entry and removes the entry from the queue. Peek() returns the highest-priority element in the queue without removing it.

43
Q

What is a ArrayDeque?

A

ArrayDeque is a Collection class that implements the Deque interface. As we described earlier, Deque is an interface for double-ended queues, with methods for adding and removing elements to and from the queue at either end.

44
Q

What is the main advantage of ArrayDeque?

A

The main advantage of ArrayDeque is performance. Unlike PriorityQueue, there is no natural ordering in ArrayDeque; it is simply a collection of elements that are stored in the order in which you add them.

45
Q

Method voor ArrayDeque?

A
  • offer() : add on the end
  • offerFirst() : add on the front
  • push() : add on the front
  • add() : add on the end
  • addFirst() : add on the front
  • pop() : removes the first element from the deque and returns it. Same as poll()
  • pollLast() : which removes the last element from the deque.
  • removeLast(): remove the remaining elements from the end of the deque
46
Q

How do spaces sort work?

A

spaces sort before characters and uppercase letters sort before lowercase characters.

47
Q

Can you add a subtype of the generic type in a collection?

A

You can add a subtype of the generic type in a collection. You can’t pass an ArrayList to an
argument of ArrayList in a method, because of that the compiler and JVM behave
differently for arrays versus generic methods.