Chapter 09 Cheatsheet
- Diamond operator alone
<>cannot be used on the left side - Calling any method on
nullgives aNullPointerException - The default generic type is
Object, so if you see this:var list = new ArrayList<>();, it means the generic type isObject
Common collection methods
public boolean add(E element)public boolean remove(Object object)public boolean isEmpty()public int size()public void clear()public boolean contains(Object object)public boolean removeIf(Predicate<? super E> filter)public void forEach(Consumer<? super T> action)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/DeleteList.of(varargs): ❌ Add/Delete/ReplaceList.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
public boolean add(E element)public void add(int index, E element)public E get(int index)public E remove(int index)public default void replaceAll(UnaryOperator<E> op)public E set(int index, E e)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
public boolean add(E e)orpublic boolean offer(E e)public E element()orpublic E peek()public E remove()orpublic E poll()
Deque methods
public void addFirst(E e)orpublic boolean offerFirst(E e)public void addLast(E e)orpublic boolean offerLast(E e)public E getFirst()orpublic E peekFirst()public E getLast()orpublic E peekLast()public E removeFirst()orpublic E pollFirst()public E removeLast()orpublic E pollLast()
Stack methods
public void push(E e)public E pop()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
public void clear()- Removes all keys and values from map.public boolean containsKey(Object key)- Returns whether key is in map.public boolean containsValue(Object value)- Returns whether value is in map.public Set<Map.Entry<K,V>> entrySet()- Returns Set of key/value pairs.public void forEach(BiConsumer<K key, V value>)- Loops through each key/value pair.public V get(Object key)- Returns value mapped by key or null if none is mapped.public V getOrDefault(Object key, V defaultValue)- Returns value mapped by key or default value if none is mapped.public boolean isEmpty()- Returns whether map is empty.public Set<K> keySet()- Returns set of all keys.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.public V put(K key, V value)- Adds or replaces key/value pair. Returns previous value or null.public V putIfAbsent(Key key, V value)- Adds value if key not present and returns null. Otherwise, returns existing value.public V remove(Object key)- Removes and returns value mapped to key. Returns null if none.public replace(K key, V value)- Replaces value for given key if key is set. Returns original value or null if none.public void replaceAll(BiFunction<K, V, V> func)- Replaces each value with results of functions.public int size()- Returns number of entries(key/value pairs) in map.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
- 直接把你要的 generic type 写在 diamond operator 里面
- 开多一个 generic class 来 implement 你的 generic interface
- 直接不用 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()
0means the current object is equivalent to the argument tocompareTo()Less than 0means the current object is smaller than the argument tocompareTo()More than 0means the current object is larger than the argument tocompareTo()