Collections Flashcards
What classes extend List?
ArrayList, LinkedList
What classes extend Queue?
LinkedList, Deque
What classes extend Set?
HashSet, TreeSet
What classes extend Map?
HashMap, TreeMap
What is characteristic for ArrayList?
+ quick retrieval of items
- slow add and remove of items
What is characteristic for LinkedList?
+ quick add items to start and end
- slow retrieval via index
What is characteristic for Deque?
+ quick add items to start and end
- slow retrieval via index
What is characteristic for HashSet?
+ quick add of items and duplicate check
- sort is removed
What is characteristic for TreeSet?
+ sorting
- slow add of items
Objects added to TreeSet need to implement?
Comparable interface
What is characteristic for HashMap?
+ quick adding and retrieval of items
- no sort
What is characteristic for TreeMap?
+ sorted
- slow add and retrieval of items
What does equal method in Map and Set do?
It checks if key-value pairs in Maps are the same, or values in Set are the same between to collections. Order is not checked, except in some collections like LinkedHashMap
How can collections be initialized?
Trough construction initialization and immutable factory methods - of(), asList() and copyOf().
What happens if you try and change immutable collections?
RuntimeException is thrown
When initializing new ArrayList, can diamond operator be used with var type?
Yes, compiler implicitly adds Object to diamond operator
What is the rule about collections that have auto. sort?
They cannot contain null values
MAP: Map.of()
Creates an immutable map containing zero or a specified number of entries
How do we create an immutable map containing zero or a specified number of entries?
Map.of()
MAP: Map.ofEntries()
Creates an immutable map with multiple entries
How do we create an immutable map with multiple entries?
Map.ofEntries()
MAP: Map.entry()
Creates a map entry (key-value pair) for use in map creation methods
How do we create a map entry (key-value pair) for use in map creation methods?
Map.entry()
MAP: containsKey()
Returns true if the map contains the specified key
How do we check if a map contains a specific key?
containsKey()
MAP: containsValue()
Returns true if the map contains the specified value
How do we check if a map contains a specific value?
containsValue()
MAP: merge()
Combines two maps or adds a key-value pair if the key doesn’t exist
How do we combine two maps or add a key-value pair if the key doesn’t exist?
merge()
MAP: putIfAbsent()
Adds a key-value pair to the map if the key is not already present
How do we add a key-value pair to a map if the key is not already present?
putIfAbsent()
MAP: forEach()
Iterates through each entry in the map and performs a specified action
MAP: replace()
Replaces the entry for a key only if it’s currently mapped to a specific value
QUEUE: element()
Retrieves, but does not remove, the head of the queue