Chapter 09: Collections and Generics
Cheatsheet

Chapter 09 Cheatsheet

  • Diamond operator alone <> cannot be used on the left side
  • Calling any method on null gives a NullPointerException
  • The default generic type is Object, so if you see this: var list = new ArrayList<>();, it means the generic type is Object

Common collection methods

  1. public boolean add(E element)
  2. public boolean remove(Object object)
  3. public boolean isEmpty()
  4. public int size()
  5. public void clear()
  6. public boolean contains(Object object)
  7. public boolean removeIf(Predicate<? super E> filter)
  8. public void forEach(Consumer<? super T> action)
  9. boolean equals(Object object)

1️⃣ List interface

  • Ordered
  • Allow duplicates
  • ArrayList
    • ✅ Fast accessing
    • ❌ Slow adding/removing
  • LinkedList
    • List + Deque
    • ✅ Fast accessing/adding/removing from the beginning and end of the list
    • ❌ Slow when it's an arbitrary index

Factory list creation

  • Arrays.asList(varargs): ✅ Replace ❌ Add/Delete
  • List.of(varargs): ❌ Add/Delete/Replace
  • List.copyOf(collection): ❌ Add/Delete/Replace

Constructor list creation

  • Without argument: var linked1 = new LinkedList<String>;
  • LinkedList argument: var linked2 = new LinkedList<String>(linked1);
  • Number argument: var linked3 = new LinkedList<String>(10)

List methods

  1. public boolean add(E element)
  2. public void add(int index, E element)
  3. public E get(int index)
  4. public E remove(int index)
  5. public default void replaceAll(UnaryOperator<E> op)
  6. public E set(int index, E e)
  7. public default void sort(Comparator<? super E> c)

2️⃣ Set interface

  • No duplicates
  • HashSet
    • ✅ Fast accessing/adding
    • ❌ Unsorted, unordered
  • TreeSet
    • ✅ Maintain natural sorted order
    • ❌ Slow accessing/adding

Factory set creation

  • Set<Character> letters = Set.of('z', 'o', 'o')
  • Set<Character> copy = Set.copyOf(letters)

Queue & Deque interfaces

  • Understand what is FIFO queue, LIFO stack, and double-ended queue

Queue methods

  1. public boolean add(E e) or public boolean offer(E e)
  2. public E element() or public E peek()
  3. public E remove() or public E poll()

Deque methods

  1. public void addFirst(E e) or public boolean offerFirst(E e)
  2. public void addLast(E e) or public boolean offerLast(E e)
  3. public E getFirst() or public E peekFirst()
  4. public E getLast() or public E peekLast()
  5. public E removeFirst() or public E pollFirst()
  6. public E removeLast() or public E pollLast()

Stack methods

  1. public void push(E e)
  2. public E pop()
  3. public E peek()

3️⃣ Map interface

  • Keys & values
  • HashMap
    • Stores keys in hash table
    • ✅ Fast accessing/adding
    • ❌ Unordered
  • TreeMap
    • ✅ Maintain natural sorted order
    • ❌ Slow accessing/adding

Factory map creation

  • Map<String, Integer> map = Map.of("key1", 1, "key2", 2)
  • Map<String, Integer> copy = Map.copyOf(map)
  • Map.ofEntries(Map.entry("key1", "value1"), Map.entry("key1", "value2"));

Map methods

  1. public void clear() - Removes all keys and values from map.
  2. public boolean containsKey(Object key) - Returns whether key is in map.
  3. public boolean containsValue(Object value) - Returns whether value is in map.
  4. public Set<Map.Entry<K,V>> entrySet() - Returns Set of key/value pairs.
  5. public void forEach(BiConsumer<K key, V value>) - Loops through each key/value pair.
  6. public V get(Object key) - Returns value mapped by key or null if none is mapped.
  7. public V getOrDefault(Object key, V defaultValue) - Returns value mapped by key or default value if none is mapped.
  8. public boolean isEmpty() - Returns whether map is empty.
  9. public Set<K> keySet() - Returns set of all keys.
  10. public V merge(K key, V value, Function(<V, V, V> func)) - Sets value if key not set. runs function if key is set, to determine new value. Removes if value is null.
  11. public V put(K key, V value) - Adds or replaces key/value pair. Returns previous value or null.
  12. public V putIfAbsent(Key key, V value) - Adds value if key not present and returns null. Otherwise, returns existing value.
  13. public V remove(Object key) - Removes and returns value mapped to key. Returns null if none.
  14. public replace(K key, V value) - Replaces value for given key if key is set. Returns original value or null if none.
  15. public void replaceAll(BiFunction<K, V, V> func) - Replaces each value with results of functions.
  16. public int size() - Returns number of entries(key/value pairs) in map.
  17. public Coleection<V> values() - Returns Collection of all values.

Generics

  • Generic type 可以用在 class,interface,method(static + non-static),records
  • 可以把 generic 想象成在 TypeScript 里我们需要给 parameter 的 type
  • Type erasure 是为了让有 generic 的 code 最终被 compile 成没有 generic 的 code,使得在 generic 还没推出之前的 code 还能够运行
  • Polymorphism 只适用在 return base type, 而非 generic parameter type。这个问题可以使用 wildcard generic type 来解决
  • 需要清楚了解 method overloading 和 method overriding 之间的差别

Ways to implement Generic interfaces

  1. 直接把你要的 generic type 写在 diamond operator 里面
  2. 开多一个 generic class 来 implement 你的 generic interface
  3. 直接不用 generics,把 type 写成 Object 就行,但是 compiler 会警告你说那将会是个 raw type

Bounding generic types

Wildcards can only be on the left side

Unbounded wildcard

  • ?
  • read-only, immutable
  • 可以把它想象成 TypeScript 里的any

Upper bound wildcard

  • ? extends type
  • read-only, immutable
  • 可以把 upper bound 想象成 compiler 能接受最高的 type 是 extends 后面说的 type,比那个 type 更高的 type 将会报错

Lower bound wildcard

  • ? super type
  • non-immutable
  • lower bound 就和 upper bound 相反。在 super 后面说的 type 是 compiler 能接受最低的 type,比那个 type 更低的将会报错

Sorting data

  • Numbers sort in numerical order
  • String objects sort in this order (number -> uppercase letter -> lowercase letter)

compareTo()

  • 0 means the current object is equivalent to the argument to compareTo()
  • Less than 0 means the current object is smaller than the argument to compareTo()
  • More than 0 means the current object is larger than the argument to compareTo()