Заметки по теме Collections в Java 8. Это задумывалось как большая продуманная статья, но обстоятельства заставляют срочно и полностью переключиться на другой проект, так что выкладываю в формате заметок. Пара последних классов остались без русскоязычного описания, вникайте сами.

Кроме приведённых интерфейсов все классы также реализуют Cloneable и Serializable. (Своеобразное исключение составляет LinkedHashMap, но он является расширением HashMap, который реализует.). В спойлерах даны отдельные выдержки из TutorialsPoint.com и из описания класса, приведённого в начале его кода, которое соотверствует документации, выложенной на сайте Oracle.
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess
TutorialsPoint.com, docs.oracle.com, Guru99.com
Выдержки из описаний (Eng)
ArrayList supports dynamic arrays. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.
The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
ArrayList - почти как обычный массив, но позволяет дополнительно изменять размер. Внутренняя структура ArrayList представляет из себя обычный массив. Его начальный размер по умолчанию составляет 10 элементов, пользователь может задать свой. Когда этот массив заполнится, то создаётся новый с ёмкостью в полтора раза больше, и старые данные туда перепивываются.
Операции size, isEmpty, get, set, iterator и listIterator происходят за постоянное время, не зависящее от размера массива, O(1). Операция add происходит за амортизированное постоянное время (amortized constant time). Т.е. в большинстве случаев происходит за линейное время, но при некоторых пороговых величинах массива могут быть небольшие задержки, связанные с тем, что Java перестраивает внутренний массив. Подробнее об амортизированном времени можно прочитать на stackoverflow.com и bambielli.com. Все другие операции, грубо говоря, протекают за линейное время, O(n). Быстрее, чем в случае с LinkedList.
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>
TutorialsPoint.com, docs.oracle.com
Выдержки из описаний (Eng)
LinkedList provides a linked-list data structure.
AbstractSequentialList extends AbstractList for use by a collection that uses sequential rather than random access of its elements.
Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).
All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
LinkedList представляет из себя Doubly LinkedList структуру, где каждый элемент содержит ссылки на предыдущий и следующий узел. Структура удобна в случае, если в процессе работе нужно часто перестраивать массив, добавляя туда новые элементы и удаляя старые. Однако более медленна, если необходим доступ к элементу по индексу.
public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>
TutorialsPoint.com, docs.oracle.com
Выдержки из описаний (Eng)
—
Resizable-array implementation of the Deque interface. Array deques have no capacity restrictions; they grow as necessary to support usage. Null elements are prohibited. This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue.
Most ArrayDeque operations run in amortized constant time. Exceptions include remove, removeFirstOccurrence, removeLastOccurrence, contains, iterator.remove(), and the bulk operations, all of which run in linear time.
...
This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.
ArrayDeque является более упрощённым воплощением Deque-интерфейса по сравнению с LinkedList. Структура динамически расширяется. Вставка элемента null невозможна. Большинство ArrayDeque-операций происходят в амортизированное постоянное время (amortized constant time), O(1). Исключение составляют remove, removeFirstOccurrence, removeLastOccurrence, contains, iterator.remove() и bulk-операций, которые имеют линейную зависимость от количества элементов, O(n).
Если необходимо реализовать только queue-операции (такие как вставка новых элементов, удаление существующих, последовательный перебор), а доступ по индексу не важен, то эта структура быстрее LinkedList. На больших очередях элементов разница в скорости может быть трёхкратной. Где возможно, следует предпочитать ArrayDeque.
Главные отличия от ArrayDeque от LinkedList: не поддерживает List-операции (такие как доступ по индексу) и не позволяет использовать null.
public class HashSet<E> extends AbstractSet<E> implements Set<E>
TutorialsPoint.com, docs.oracle.com
Выдержки из описаний (Eng)
HashSet creates a collection that uses a hash table for storage. A hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code. The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically.
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
HashSet - набор уникальных данных. Каждое значение может присутствовать только в одном экземпляре. Включая null. В HashSet порядок ввода данных не сохраняется и не имеет значения, взаимное расположение элементов внутри структуры может измениться. Время поиска, вставки и удаления элементов постоянно, O(1). Внутренне использует HashMap, где значение key генерируется hash-функцией и обеспечивает более-менее равномерное распределение элементов.
public class LinkedHashSet<E> extends HashSet<E> implements Set<E>
TutorialsPoint.com, docs.oracle.com
Выдержки из описаний (Eng)
LinkedHashSet extends HashSet. It additionally maintains a linked list of the entries in the set, in the order in which they were inserted. This allows insertion-order iteration over the set. That is, when cycling through a LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted.
Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)
This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashSet, without incurring the increased cost associated with TreeSet. It can be used to produce a copy of a set that has the same order as the original, regardless of the original set's implementation:
void foo(Set s) {
Set copy = new LinkedHashSet(s);
...
}
This technique is particularly useful if a module takes a set on input, copies it, and later returns results whose order is determined by that of the copy. (Clients generally appreciate having things returned in the same order they were presented.)
This class provides all of the optional Set operations, and permits null elements. Like HashSet, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list, with one exception: Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity.
A linked hash set has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashSet. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashSet, as iteration times for this class are unaffected by capacity.
LinkedHashSet расширяет HashSet, накладывая поверх него Doubly Linked List. Благодаря этому сохраняется порядок вставки элементов и с ними можно проделывать операции, характерные для Doubly Linked List. Операции поиска, вставки и удаления элементов имеют постоянное время, O(1). Перебор элементов происходит быстрее, чем в HashSet. Добавления элемента со значением, уже имеющимся в наборе, порядок элементов не изменяет - такой элемент игнорируется. Внутренне используется LinkedHashMap.
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>
TutorialsPoint.com, docs.oracle.com
Выдержки из описаний (Eng)
TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in a sorted and ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly.
A NavigableSet implementation based on a TreeMap. The elements are ordered using their Comparable natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
TreeSet является набором данных, в которой элементы сразу располагаются в отсортированном порядке. Некоторые конструкторы позволяют пользователю задать Comparator, который определяет правило сортировки элементов. Время поиска, добавления и удаления элементов зависит от величины набора логарифмически, O(log(n)). Внутренне использует TreeMap.
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>
TutorialsPoint.com, docs.oracle.com, Guru99.com
Выдержки из описаний (Eng)
HashMap uses a hashtable to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets.
Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.
As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.
If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table. Note that using many keys with the same hashCode() is a sure way to slow down performance of any hash table. To ameliorate impact, when keys are Comparable, this class may use comparison order among keys to help break ties.
HashMap каждый элемент имеет сохраняемое значение и уникальный ключ, по которому это значение отыскивается. В том числе разрешается один null-ключ. Порядок ввода данных не сохраняется и не имеет значения, взаимное расположение элементов внутри структуры может измениться. Время выполнения базовых операций (get, put, remove) постоянно, O(1).
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
TutorialsPoint.com, docs.oracle.com
Выдержки из описаний (Eng)
LinkedHashMap extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted. You can also create a LinkedHashMap that returns its elements in the order in which they were last accessed.
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)
This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashMap (and Hashtable), without incurring the increased cost associated with TreeMap. It can be used to produce a copy of a map that has the same order as the original, regardless of the original map's implementation:
void foo(Map m) {
Map copy = new LinkedHashMap(m);
...
}
This technique is particularly useful if a module takes a map on input, copies it, and later returns results whose order is determined by that of the copy. (Clients generally appreciate having things returned in the same order they were presented.)
A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). This kind of map is well-suited to building LRU caches. Invoking the put, putIfAbsent, get, getOrDefault, compute, computeIfAbsent, computeIfPresent, or merge methods results in an access to the corresponding entry (assuming it exists after the invocation completes). The replace methods only result in an access of the entry if the value is replaced. The putAll method generates one entry access for each mapping in the specified map, in the order that key-value mappings are provided by the specified map's entry set iterator. No other methods generate entry accesses. In particular, operations on collection-views do not affect the order of iteration of the backing map.
The removeEldestEntry(Map.Entry) method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map.
This class provides all of the optional Map operations, and permits null elements. Like HashMap, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashMap, due to the added expense of maintaining the linked list, with one exception: Iteration over the collection-views of a LinkedHashMap requires time proportional to the size of the map, regardless of its capacity. Iteration over a HashMap is likely to be more expensive, requiring time proportional to its capacity.
A linked hash map has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashMap. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap, as iteration times for this class are unaffected by capacity.
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>
TutorialsPoint.com, docs.oracle.com
Выдержки из описаний (Eng)
TreeMap implements the Map interface by using a tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. You should note that, unlike a hash map, a tree map guarantees that its elements will be sorted in an ascending key order.
A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest's Introduction to Algorithms.
Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.
Comments
Excellent explanation on…
Excellent explanation on java collections.
Thanks,
https://www.flowerbrackets.com/arraylist-in-java/