Java Collections
Enumeration vs. Iteration
-Only traverses the collection vs. also can remove an element from the collection -Fail-safe vs. fail-fast (ConcurrentModificationException) -Not safe and secure vs. is Methods: hasMoreElements() and nextElement() vs. hasNext(), next() and remove()
core collection interfaces
Foundation of Collections Framework Generally, non-concurrent, unsynchronized, don't support primitives Hierarchy: Tree 1: Collection --> Set, List, Queue, Deque Set --> SortedSet Tree 2: Map --> SortedMap (not a true collection)
Arrays pros and cons
Pros Easy to create, Easy to use Direct indexing: O(1) Sequential access: O(N) Cons Sorting: O(NLogN) Searching: O(N), and O(LogN) if sorted Inserting and deleting: O(N) because of shifting items.
conversion constructor
A constructor that converts the passed collection type to the an object of the constructor's class. Example: Collection<String> c; List<String> list = new ArrayList<>(c);
Collections Framework
A unified architecture for representing and manipulating collections. Consists of: -Collection interfaces, the basis of the framework. -Implementations, such as general-purpose, legacy, special-purpose, concurrent, wrapper, convenient and abstract. -Algorithms, static methods that perform useful functions on collections, such as sorting a list. - Infrastructure, interfaces that provide essential support for the collection interfaces. - Array Utilities, utility functions for arrays of primitive types and reference objects. Not, strictly speaking, a part of the collections framework
Hashmap vs Hashtable
Allows null values and one null key vs. No null key or null values Non synchronized vs synchronized
Aggregate operations vs. iterators
Internal iteration (parallel computing, non-sequential iteration) vs. external (sequential iteration) Process elements from a stream vs. from a collection Support behaviors as parameters by using lambda expressions vs. don't Example: forEach();
Summary
The first tree starts with the Collection interface, which provides for the basic functionality used by all collections, such as add and remove methods. The Set interface does not allow duplicate elements. The List interface provides for an ordered collection, for situations in which you need precise control over where each element is inserted. You can retrieve elements from a List by their exact position. The Queue interface enables additional insertion, extraction, and inspection operations. Elements in a Queue are typically ordered in on a FIFO basis. The Deque interface enables insertion, deletion, and inspection operations at both the ends. Elements in a Deque can be used in both LIFO and FIFO. The second tree starts with the Map interface, which maps keys and values similar to a Hashtable. Map's subinterface, SortedMap, maintains its key-value pairs in ascending order or in an order specified by a Comparator.
SortedSet interface
What: A Set, elements in ascending order sorted according to natural ordering or to a Comparator provided at creation time. Operations besides those provided by Set: Range view — allows arbitrary range operations on the sorted set Endpoints — returns the first or last element in the sorted set Comparator access — returns the Comparator, if any, used to sort the set Operation exceptions compared to Set: The Iterator returned by the iterator operation traverses the sorted set in order. The array returned by toArray contains the sorted set's elements in order. public interface SortedSet<E> extends Set<E> { // Range-view SortedSet<E> subSet(E fromElement, E toElement); SortedSet<E> headSet(E toElement); SortedSet<E> tailSet(E fromElement); // Endpoints E first(); E last(); // Comparator access Comparator<? super E> comparator(); }
Set Interface
What: A general collection of objects with no order. Extends Collection but has no methods. public interface Set<E> extends Collection<E> Pros: -Best for bulk operations -Don't allow duplicates Cons: -Sucks at everything else Allows duplicates: no Allows null: no, only one Random access: by value Implementations: HashSet, best, stores elements in hash table with no iteration order guarantee. TreeSet, slow, stores elements in red-black tree, orders by element values. LinkedHashSet, slightly worse than HashSet, hash table with a linked list running through it, order based on order of element insertion. Basic operations: size, isEmpty, remove, add, iterator Bulk operations: s1.containsAll(s2), s1.addAll(s2), s1.retainAll(s2), s1.removeAll(s2) Array operations: Same as collections
Collection interface
What: A group of objects with no particular restrictions (e.g., a Bag) public interface Collection<E> extends Iterable<E> Two constructors should be provided: Void (no argument) constructor - create an empty Collection Collection as argument - create a Collection containing same elements as constructor argument Methods: Has methods that tell you how many elements are in the collection (size, isEmpty), methods that check whether a given object is in the collection (contains), methods that add and remove an element from the collection (add, remove), and methods that provide an iterator over the collection (iterator). Collection<String> nameCollection; Bulk operations: perform an operation on an entire Collection like containsAll, addAll, removeAll, retainAll, clear Array Operations: provided as a bridge between collections and older APIs that expect arrays on input. The array operations allow the contents of a Collection to be translated into an array.
Collections vs. streams:
What: A sequence of elements from a source that supports aggregate operations from java.util.streams Collections vs. streams: In-memory data structures which hold elements that were computed before insertion vs. lazily constructed collections, behave opposite to collections, fixed data structures which computes the elements on-demand basis. Stream interface: public interface Stream<T> extends BaseStream<T,Stream<T>>
Map interface
What: An object that maps keys to values, with one value per unique key. Part of collection framework but is the basis of its own tree, does not extend collection. Syntax: public interface Map<K,V> Pros: -Used to group data like a database table -Most versatile and useful collection -Does everything fast regardless of size Cons: -Don't want key value pairs -Mutable objects shouldn't be used as keys -Few concurrent implementations Order: Comparator or comparable, determined by order of elements returned by Iterator Allows duplicates: no Allows null: yes Method: Basic operations: put, get, remove, containsKey, containsValue, size, and empty Bulk operations: putAll and clear Collection views: keySet, entrySet, and values Implementations: Single-threaded: HashMap - most used, best performance, simple map, if iteration order is not important TreeMap - is ordered and sorted but slower compared to HashMap. TreeMap has ascending order of keys, according to its Comparator LinkedHashMap - it orders items by key during insertion Behavior and performance are precisely analogous to HashSet, TreeSet, and LinkedHashSet. Other: Single-threaded: EnumMap - enum keys Hashtable - deprecated IdentityHashMap - keys compared with == WeakHashMap - useful for caches Concurrent: ConcurrentHashMap - generic concurrent map ConcurrentSkipListMap - sorted concurrent map
Queue interface
What: Core collections interface holding elements prior to processing and provides additional insertion, removal, and inspection operations. Inserts elements at end and removes at the front like a real queue. Why: Pros: Does not use a lot of garbage collection Push/Add: O(1) Pop/Remove: O(1) Peek: O(1) Cons: No versatility, get the front or end of the line and thats it public interface Queue<E> extends Collection<E> { E element(); boolean offer(E e); E peek(); E poll(); E remove(); } Speed: Fast Order: FIFO Allows duplicates: yes Allows null: no Implementations: Single threaded: Stack - deprecated PriorityQueue - sorted retrieval operations Concurrent: ArrayBlockingQueue - bounded blocking queue ConcurrentLinkedQueue - unbounded linked queue (CAS) DelayQueue - queue with delays on each element LinkedBlockingQueue - optionally bounded linked queue (locks) LinkedTransferQueue - may transfer elements w/o storing PriorityBlockingQueue - concurrent PriorityQueue SynchronousQueue - Exchanger with Queue interface Two forms of methods if operation fails: 1. Throws exception, such as add(e), remove( ), element( ) 2. Returns special value like null or false, such as offer(e), poll( ), peek( )
Deque (deck)
What: Core collections interface, double-ended-queue, allowing insertion and deletion from both ends. public interface Deque<E> extends Queue<E> Same as Queue except has FIFO and LIFO Implementations: Single threaded: ArrayDeque - generic array-based Concurrent: ConcurrentLinkedDeque - unbounded linked deque LinkedBlockingDeque - optionally bounded linked deque Methods: Throw exceptions or return a unique value if a specified element cannot be found Insert: addFirst(e), addLast(e) offerFirst(e), offerLast(e) Remove: removeFirst(), removeLast() pollFirst(), pollLast() Examine: getFirst(), getLast() peekFirst(), peekLast()
ArrayList
What: Core collections most common class implementation of List, dynamically sized array public class ArrayList<E> extends AbstractList<E> implements List<E> Pros: -Cache friendly because backed by array, less cache friendly than an array -Used to store objects, not primitives like arrays -Updating tail is cheap, updating head is expensive, everything to the right from the update position must be moved to the right for insertions and to the left for removals Cons: -Slower than regular array, but faster than LinkedList -Gets slower as it gets larger Big O: O(1) for random access by index, O(n) for insertion and deletion Order: Determined by user, or natural Random access: index Syntax: private ArrayList<String> groceryList = new ArrayList<String>(); Methods: groceryList.get(position), .add, .set, .remove, .contains, .indexOf
SortedMap interface
What: Extends map, maintains order in ascending order sorted according to the keys' natural ordering, or to a Comparator provided at creation. Like map with an order Operations other than regular map operations: Range view: performs arbitrary range operations Endpoints: returns the first or the last key Comparator access: returns the Comparator Four constructors should be provided: Void (no argument) constructor - create an empty SortedMap Collection as argument - create a SortedMap containing same elements as constructor argument ordering follows elements natural order Comparator as argument - create an empty SortedMap ordering is managed by Comparator SortedMap as argument - create a SortedMap with same elements as argument. public interface SortedMap<K, V> extends Map<K, V>{ Comparator<? super K> comparator(); SortedMap<K, V> subMap(K fromKey, K toKey); SortedMap<K, V> headMap(K toKey); SortedMap<K, V> tailMap(K fromKey); K firstKey(); K lastKey(); } Map operations with exceptions: - Iterator traverse the collections in order. - toArray arrays contain the keys, values, or entries in order. - Not guaranteed, the toString method of the Collection views in all the Java platform's SortedMap implementations returns a string containing all the elements of the view, in order.
Comparable Interface
What: Interface consisting of a single method that encapsulates a natural ordering for collection elements of specific types, implemented when the collection is sorted. public interface Comparable<T> { public int compareTo(T o); } Class Natural Ordering Signed numerical: Byte, Long, Integer, Short, Double, Float, BigInteger, BigDecimal Unsigned numerical: Character Boolean.FALSE < Boolean.TRUE: Boolean System-dependent lexicographic on path name: File Lexicographic: String Chronological: Date Locale-specific lexicographic: Collation Key
Comparator interface
What: Interface consisting of a single method that encapsulates a non-natural/non-comparable ordering for collection elements, implemented when the collection is sorted. public interface Comparator<T> { int compare(T o1, T o2); }
LinkedList
What: Linear data structure storing elements non-contiguously, where each element (node) contains data and the address to the next node. Pros and cons: -has fast adding to the start of the list, and fast deletion from the interior via iteration, at the expense of complex structure -Only sequential access of elements. (In other words, accessing any element requires iterating over all previous elements.) - Effectively uses memory, but is slow public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable Big O: O(n) for random access by index, O(1) for insertion and deletion Size: Resizable according to use Order: FIFO or LIFO Random access: node Syntax: java.util.LinkedList LinkedList<Object> linkedList = new LinkedList<>();
List
What: Ordered core collection interface, aka sequence public interface List<E> extends Collection<E> Pros and cons: -for situations in which you need precise control over where each element is inserted, and maintains this order. -You can retrieve elements from a List by their exact position -many List specific algorithms allowing diverse manipulation Allows duplicates: yes Allows null: yes Random access: index Methods: Positional access Search Iteration Range-view Implementations: Single threaded: ArrayList - generic array-based LinkedList - do not use Vector - deprecated Concurrent: CopyOnWriteArrayList - seldom updated, often traversed
collection vs Collection vs Collections
collection : A collection(with small 'c') represents a group of objects/elements. Collection : The root interface in the Collections hierarchy Collections : A utility class that is a member of the Java Collections Framework.
Collections class
java.util.Collections Class that consists exclusively of static methods that operate on or return Collections.