какие методы есть у класса collections
Работа с коллекциями на Java
Интерфейс Java Collection(java.util.Collection) является одним из корневых интерфейсов API Java Collection. Хотя не создаете экземпляр Collection напрямую, а скорее подтип Collection, вы часто можете рассматривать эти подтипы единообразно, как Collection. В этом тексте вы увидите как.
Создание
Вы не создаете экземпляр Collection напрямую, но экземпляр одного из подтипов Collection. Вот пример создания List, который является подтипом Collection:
Приведенный выше пример работает для каждого подтипа коллекции.
Подтипы
Следующие интерфейсы (типы коллекций) расширяют интерфейс Java Collection:
Java не поставляется с удобной реализацией интерфейса Collection, поэтому вам придется использовать один из перечисленных подтипов. Интерфейс просто определяет набор методов (поведения), которые разделяет каждый из этих подтипов. Это позволяет игнорировать конкретный тип коллекции, которую вы используете, и просто рассматривать ее как коллекцию.
Пример стандартного наследования, так что в этом нет ничего волшебного, но время от времени может быть хорошей особенностью.
Вот метод, который работает с коллекцией:
И вот несколько способов вызвать этот метод с разными подтипами Collection:
Как добавить элемент
Независимо от того, какой подтип вы используете, существует несколько стандартных методов для добавления элементов в коллекцию. Осуществляется это с помощью метода add():
Метод add() добавляет данный элемент в коллекцию и возвращает true, если коллекция изменилась в результате вызова метода. Может и не измениться. Если набор уже содержал этот элемент, он больше не добавляется. С другой стороны, если бы вы вызвали add() для List, и список уже содержал этот элемент, в итоге элемент дважды существовал бы в List.
Как удалить элемент
Метод remove() удаляет элемент из коллекции и возвращает значение true, если удаленный элемент присутствовал в коллекции и был удален. Если отсутствует, метод возвращает false. Вот пример удаления:
Как добавить коллекцию объектов
Для этого используйте addAll():
Java Collection addAll() добавляет все элементы, найденные в Collection, переданные в качестве параметра в метод. Сам объект не добавляется, только его элементы. Если бы вы вызвали add() с Collection в качестве параметра, был бы добавлен сам объект, а не его элементы.
Как именно ведет себя метод addAll(), зависит от подтипа Collection. Некоторые подтипы позволяют добавлять один и тот же элемент более одного раза, а другие – нет.
Как удалить коллекцию элементов
Java Collection removeAll() удаляет все найденные элементы, переданные Collection в качестве параметра методу. Если параметр содержит какие-либо элементы, не найденные в целевой коллекции, они просто игнорируются. Вот пример удаления:
Как сохранить все элементы из коллекции в другой
Коллекция Java retainAll() является противоположностью removeAll(). Вместо удаления всех элементов, найденных в параметре Collection, он сохраняет их и удаляет все остальные.
Имейте в виду, что только если элементы уже содержались в целевой коллекции, они сохраняются. Любые новые элементы, найденные в параметре, которых нет в целевой коллекции, не добавляются автоматически. Они просто игнорируются.
Проверка, содержится ли определенный элемент
Интерфейс Collection имеет два метода, чтобы проверить, содержит ли Collection один или несколько определенных элементов. Это методы contains() и containsAll(). Они проиллюстрированы здесь:
Размер
Вы можете проверить размер коллекции, используя метод size(). Под «размером» подразумевается количество элементов. Вот пример:
Итерация
Вы можете перебрать все элементы коллекции. Это делается путем получения Java Iterator из коллекции и повторения этого. Вот как это выглядит:
Вы также можете выполнить итерацию Java Collection с помощью цикла for-each:
Коллекции в Java
2020.06.08 (Последнее изменение: 2021.07.15)
Общее описание
Интерфейсы коллекций
Иерархия интерфейсов коллекций
Интерфейс | Описание |
---|---|
Itarable | Реализация данного интерфейса позволяет объекту использоваться в цикле “for-each” |
Collection | Корневой интерфейс в иерархии коллекций. |
List | Упорядоченная коллекция (также известная как последовательность). |
Set | Коллекция (набор/множество), которая не содержит повторяющихся элементов. |
SortedSet | Интерфейс Set, который дополнительно обеспечивает упорядочение по его элементам. |
NavigableSet | Интерфейс SortedSet расширенный с помощью методов навигации, обеспечивающих поиск ближайших совпадений искомых элементов. |
Queue | Очередь, предназначенна для хранения элементов перед обработкой. |
Deque | Линейная коллекция, которая поддерживает вставку и удаление элементов на обоих концах. |
Map | Отображение. Объект, который сопоставляет ключи со значениями. |
SortedMap | Отображение, которое дополнительно обеспечивает упорядочивание по ключам. |
NavigableMap | Интерфейс SortedMap расширенный с помощью методов навигации, обеспечивающих поиск ближайших совпадений искомых элементов. |
Iterator | Итератор по коллекции. |
ListIterator | Итератор для списков, который позволяет программисту перемещаться по списку в любом направлении, изменять список во время итерации и получать текущее положение итератора в списке. |
RandomAccess | Маркерный интерфейс, используемый реализациями списков для указания на то, что они поддерживают быстрый (обычно постоянный по времени) произвольный доступ. |
Интерфейс | Описание |
---|---|
Cloneable | Позволяет классам, реализующим интерфейс, сделать копию экземпляра класса. |
Serializable | Интерфейс позволяет классу быть сериализованным, это означает что объект класса может быть преобразован в последовательность бит или байт для передачи по сети. |
Интерфейс Map
Отображение. Структура данных для хранения связанных вместе пар “ключ-значение”.
public interface Map
Вложенные классы
Класс | Описание |
---|---|
static interface Map.Entry | Запись отображения (пара ключ-значение отображения). Получается с помощью метода Map.entrySet() |
Метод | Описание |
---|---|
K getKey() | Возвращает ключ соответствующий данной записи. |
V getValue() | Возвращает значение соответствующее данной записи. |
V setValue(V value) | Заменяет значение соответствующее этой записи на указанное значение (опциональная операция). |
Методы
Наиболее общие реализации сведены в следующей таблице:
Interface | Hash Table | Resizable Array | Balanced Tree | Linked List | Hash Table + Linked List |
---|---|---|---|---|---|
Set | HashSet | TreeSet | LinkedHashSet | ||
List | ArrayList | LinkedList | |||
Deque | ArrayDeque | LinkedList | |||
Map | HashMap | TreeMap | LinkedHashMap |
Свойства коллекций
Временная сложность
Среднее | Индекс | Поиск | Вставка | Удаление |
---|---|---|---|---|
ArrayList | O(1) | O(n) | O(n) | O(n) |
Vector | O(1) | O(n) | O(n) | O(n) |
LinkedList | O(n) | O(n) | O(1) | O(1) |
Hashtable | n/a | O(1) | O(1) | O(1) |
HashMap | n/a | O(1) | O(1) | O(1) |
LinkedHashMap | n/a | O(1) | O(1) | O(1) |
TreeMap | n/a | O(log(n)) | O(log(n)) | O(log(n)) |
HashSet | n/a | O(1) | O(1) | O(1) |
LinkedHashSet | n/a | O(1) | O(1) | O(1) |
TreeSet | n/a | O(log(n)) | O(log(n)) | O(log(n)) |
Худшее | Индекс | Поиск | Вставка | Удаление |
---|---|---|---|---|
ArrayList | O(1) | O(n) | O(n) | O(n) |
Vector | O(1) | O(n) | O(n) | O(n) |
LinkedList | O(n) | O(n) | O(1) | O(1) |
Hashtable | n/a | O(n) | O(n) | O(n) |
HashMap | n/a | O(n) | O(n) | O(n) |
LinkedHashMap | n/a | O(n) | O(n) | O(n) |
TreeMap | n/a | O(log(n)) | O(log(n)) | O(log(n)) |
HashSet | n/a | O(n) | O(n) | O(n) |
LinkedHashSet | n/a | O(n) | O(n) | O(n) |
TreeSet | n/a | O(log(n)) | O(log(n)) | O(log(n)) |
ArrayList
Является реализацией динамического массива объектов. Позволяет хранить любые данные, включая null в качестве элемента. Реализация основана на обычном массиве.
Следует применять, если в процессе работы с коллекцией предполагается частое обращение к элементам по индексу.
Не рекомендуется применять, если требуется частое удаление/добавление элементов в середину коллекции.
Пример использования ArrayList
Ссылки
LinkedList
Пример использования LinkedList
Ссылки:
HashSet
Пример использования хэш-множества HashSet
Ссылки:
TreeSet
Древовидное множество. Хранит отсортированную коллекцию в виде структуры красно-черного дерева.
Пример использования TreeSet
Ссылки:
EnumSet
Специализированное множество используется с типами enum (перечислениями).
Для реализации использует битовую последовательность. В каждом бите устанавливается 1, если соответствующее значение перечисления присутствует в множестве. Все методы в EnumSet реализованы с использованием арифметических побитовых операций. Эти вычисления очень быстрые, и поэтому все основные операции выполняются за постоянное время. Если сравнивать EnumSet с другими реализациями Set то он обычно быстрее, потому что значения хранятся в предсказуемом порядке, и для каждого вычисления необходимо проверять только один бит. В отличие от HashSet, нет необходимости вычислять hashcode, чтобы найти правильный сегмент. EnumSet очень компактен и эффективен. Следовательно, использует меньше памяти.
EnumSet следует использовать, когда мы храним значения enum в множестве.
Пример использования EnumSet
Ссылки:
LinkedHashSet
Множество сохраняющее значения в хэш таблицу в виде связанного списка с сохранением порядка ввода.
Сравнение LinkedHashSet и HashSet
Сравнение LinkedHashSet и TreeSet
Ссылки:
ArrayDeque
Двусторонняя очередь. Массив с изменяющимся размером, реализующий интерфейс Deque.
Сравнение ArrayDeque и LinkedList
Использование в качестве стэка
Ссылки:
PriorityQueue
Очередь по приоритету возвращает элементы в отсортированном порядке, после того как они были введены в произвольном порядке.
Например, мы хотим получить элементы в порядке возрастания. В этом случае голова очереди будет указывать на наименьший элемент. Когда элемент будет получен, следующий наименьший элемент станет головой очереди.
Элементы приоритетной очереди могут быть не отсортированы, однако элементы возвращаются в отсортированном порядке.
Ссылки:
HashMap
Отображение. Структура данных для хранения связанных вместе пар “ключ-значение”. Хэширует только ключи, значения не хэшируются. Хэширование выполняется немного быстрее, чем вставка в дерево, поэтому данные отображение используется, когда не требуется отсортированный порядок ключей.
Ссылки:
TreeMap
Отображение. Структура данных для хранения связанных вместе пар “ключ-значение”. Использует хранение ключей в виде дерева для поиска. Функция сравнения для вставки в дерево используется только для ключей, значения не сравниваются.
Ссылки:
WeakHashMap
Отображение основанное на хэш таблицах со слабыми ключами. Записи в нем автоматически будут удалены системой сборки “мусора”, если ключ не используется (на него нет ссылок, кроме WeakHashMap), при удалении ключа также будет удалено связанное значение.
Сравнение WeakHashMap и HashMap
Ссылки:
LinkedHashMap
Отображение основанное на хэш-таблицах с сохранением порядка ввода элементов или порядка доступа к элементам в двунаправленном связанном списке. Порядок доступа может быть использован при реализации кэширования с “наиболее давним использованием”. Сохраняются часто используемые элементы, а при заполнении удаляется наиболее старый элемент.
Сравнение LinkedHashMap и HashMap
Оба LinkedHashMap и HashMap реализуют интерфейс Map. Однако, существуют некоторые отличия между ними.
Ссылки:
EnumMap
Класс EnumMap специализированная реализация Map для использования типа enum в качестве ключей. Все ключи должны иметь один тип enum который явно или неявно указан при создании отображения. Внутри данный класс реализован как массивы. Такая реализация очень компактна и эффективна.
Ссылки:
IdentityHashMap
Этот класс не является реализацией общего назначения интерфейса Map! Хотя этот класс реализует интерфейс Map, он намеренно нарушает общее соглашение, которое предписывает использование метода equals() при сравнении объектов. Этот класс используется только когда требуется семантика равенства ссылок.
Класс IdentityHashMap используется, когда хэш-значения ключей должны вычисляться не методом hashCode(), а методом System.identityHashCode(). В данном методе вычисление хэш-кода происходит исходя из адреса объекта в памяти. Для сравнения объектов типа IdentityHashMap используется операция ==, а не метод equals().
Ссылки:
Представления и оболочки
Представлением называется объект реализующий интерфейс коллекции методы которого управляют исходной коллекцией.
Поддиапазоны
headSet()
tailSet()
headMap()
tailMap()
Немодифицируемые представления
В классе Collections есть методы, которые создают немодифицируемые представления коллекций. Данные представления производят динамическую проверку попытки изменить коллекцию и генерируют исключение.
Синхронизированные представления
Если обращение к коллекции происходит из нескольких потоков, то нужно исключить ее повреждение. Вместо реализации потокобезопасных классов был использован механизм представлений, чтобы сделать потокобезопасными обычные коллекции.
Проверяемые представления
Предназначены для отладки ошибок, возникающих при применении обобщенных типов. При несоответствии типа генерируется исключение типа ClassCastException.
Прочее
Сортировка и перестановка
Двоичный поиск
Алгоритмы
Взаимное преобразование коллекций и массивов
Преобразование массива в коллекцию
Преобразование коллекции в массив
В интерфейсе Interface Collection есть следующие методы:
Унаследованные коллекции
В первом выпуске java появились коллекции, применявшиеся до появления фреймворка коллекций. Они были добавлены в фреймворк коллекций.
Иерархия унаследованных классов коллекций Hashtable, Properties
Иерархия унаследованных классов коллекций Vector, Stack
Какие методы есть у класса collections
The methods of this class all throw a NullPointerException if the collections or class objects provided to them are null.
The documentation for the polymorphic algorithms contained in this class generally includes a brief description of the implementation. Such descriptions should be regarded as implementation notes, rather than parts of the specification. Implementors should feel free to substitute other algorithms, so long as the specification itself is adhered to. (For example, the algorithm used by sort does not have to be a mergesort, but it does have to be stable.)
The «destructive» algorithms contained in this class, that is, the algorithms that modify the collection on which they operate, are specified to throw UnsupportedOperationException if the collection does not support the appropriate mutation primitive(s), such as the set method. These algorithms may, but are not required to, throw this exception if an invocation would have no effect on the collection. For example, invoking the sort method on an unmodifiable list that is already sorted may or may not throw UnsupportedOperationException.
This class is a member of the Java Collections Framework.
Field Summary
Modifier and Type | Field and Description |
---|---|
static List | EMPTY_LIST |
Method Summary
Modifier and Type | Method and Description |
---|---|
static boolean | addAll(Collection c, T. elements) |
Methods inherited from class java.lang.Object
Field Detail
EMPTY_SET
EMPTY_LIST
EMPTY_MAP
Method Detail
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
The specified list must be modifiable, but need not be resizable.
Implementation note: This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.
The implementation takes equal advantage of ascending and descending order in its input array, and can take advantage of ascending and descending order in different parts of the same input array. It is well-suited to merging two or more sorted arrays: simply concatenate the arrays and sort the resulting array.
The implementation was adapted from Tim Peters’s list sort for Python ( TimSort). It uses techiques from Peter McIlroy’s «Optimistic Sorting and Information Theoretic Complexity», in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.
This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n 2 log(n) performance that would result from attempting to sort a linked list in place.
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
The specified list must be modifiable, but need not be resizable.
Implementation note: This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.
The implementation takes equal advantage of ascending and descending order in its input array, and can take advantage of ascending and descending order in different parts of the same input array. It is well-suited to merging two or more sorted arrays: simply concatenate the arrays and sort the resulting array.
The implementation was adapted from Tim Peters’s list sort for Python ( TimSort). It uses techiques from Peter McIlroy’s «Optimistic Sorting and Information Theoretic Complexity», in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.
This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n 2 log(n) performance that would result from attempting to sort a linked list in place.
binarySearch
This method runs in log(n) time for a «random access» list (which provides near-constant-time positional access). If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons.
binarySearch
This method runs in log(n) time for a «random access» list (which provides near-constant-time positional access). If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons.
reverse
This method runs in linear time.
shuffle
The hedge «approximately» is used in the foregoing description because default source of randomness is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm would choose permutations with perfect uniformity.
This implementation traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element into the «current position». Elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive.
This method runs in linear time. If the specified list does not implement the RandomAccess interface and is large, this implementation dumps the specified list into an array before shuffling it, and dumps the shuffled array back into the list. This avoids the quadratic behavior that would result from shuffling a «sequential access» list in place.
shuffle
This implementation traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element into the «current position». Elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive.
This method runs in linear time. If the specified list does not implement the RandomAccess interface and is large, this implementation dumps the specified list into an array before shuffling it, and dumps the shuffled array back into the list. This avoids the quadratic behavior that would result from shuffling a «sequential access» list in place.
This method runs in linear time.
This method runs in linear time.
This method iterates over the entire collection, hence it requires time proportional to the size of the collection.
This method iterates over the entire collection, hence it requires time proportional to the size of the collection.
This method iterates over the entire collection, hence it requires time proportional to the size of the collection.
This method iterates over the entire collection, hence it requires time proportional to the size of the collection.
rotate
Note that this method can usefully be applied to sublists to move one or more elements within a list while preserving the order of the remaining elements. For example, the following idiom moves the element at index j forward to position k (which must be greater than or equal to j): To make this concrete, suppose list comprises [a, b, c, d, e]. To move the element at index 1 (b) forward two positions, perform the following invocation: The resulting list is [a, c, d, b, e].
To move more than one element forward, increase the absolute value of the rotation distance. To move elements backward, use a positive shift distance.
If the specified list is small or implements the RandomAccess interface, this implementation exchanges the first element into the location it should go, and then repeatedly exchanges the displaced element into the location it should go until a displaced element is swapped into the first element. If necessary, the process is repeated on the second and successive elements, until the rotation is complete. If the specified list is large and doesn’t implement the RandomAccess interface, this implementation breaks the list into two sublist views around index -distance mod size. Then the reverse(List) method is invoked on each sublist view, and finally it is invoked on the entire list. For a more complete description of both algorithms, see Section 2.3 of Jon Bentley’s Programming Pearls (Addison-Wesley, 1986).
replaceAll
indexOfSubList
This implementation uses the «brute force» technique of scanning over the source list, looking for a match with the target at each location in turn.
lastIndexOfSubList
This implementation uses the «brute force» technique of iterating over the source list, looking for a match with the target at each location in turn.
unmodifiableCollection
The returned collection does not pass the hashCode and equals operations through to the backing collection, but relies on Object‘s equals and hashCode methods. This is necessary to preserve the contracts of these operations in the case that the backing collection is a set or a list.
The returned collection will be serializable if the specified collection is serializable.
unmodifiableSet
The returned set will be serializable if the specified set is serializable.
unmodifiableSortedSet
The returned sorted set will be serializable if the specified sorted set is serializable.
unmodifiableList
The returned list will be serializable if the specified list is serializable. Similarly, the returned list will implement RandomAccess if the specified list does.
unmodifiableMap
The returned map will be serializable if the specified map is serializable.
unmodifiableSortedMap
The returned sorted map will be serializable if the specified sorted map is serializable.
synchronizedCollection
It is imperative that the user manually synchronize on the returned collection when iterating over it: Failure to follow this advice may result in non-deterministic behavior.
The returned collection does not pass the hashCode and equals operations through to the backing collection, but relies on Object‘s equals and hashCode methods. This is necessary to preserve the contracts of these operations in the case that the backing collection is a set or a list.
The returned collection will be serializable if the specified collection is serializable.
synchronizedSet
It is imperative that the user manually synchronize on the returned set when iterating over it: Failure to follow this advice may result in non-deterministic behavior.
The returned set will be serializable if the specified set is serializable.
synchronizedSortedSet
It is imperative that the user manually synchronize on the returned sorted set when iterating over it or any of its subSet, headSet, or tailSet views. or: Failure to follow this advice may result in non-deterministic behavior.
The returned sorted set will be serializable if the specified sorted set is serializable.
synchronizedList
It is imperative that the user manually synchronize on the returned list when iterating over it: Failure to follow this advice may result in non-deterministic behavior.
The returned list will be serializable if the specified list is serializable.
synchronizedMap
It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views: Failure to follow this advice may result in non-deterministic behavior.
The returned map will be serializable if the specified map is serializable.
synchronizedSortedMap
It is imperative that the user manually synchronize on the returned sorted map when iterating over any of its collection views, or the collections views of any of its subMap, headMap or tailMap views. or: Failure to follow this advice may result in non-deterministic behavior.
The returned sorted map will be serializable if the specified sorted map is serializable.
checkedCollection
The generics mechanism in the language provides compile-time (static) type checking, but it is possible to defeat this mechanism with unchecked casts. Usually this is not a problem, as the compiler issues warnings on all such unchecked operations. There are, however, times when static type checking alone is not sufficient. For example, suppose a collection is passed to a third-party library and it is imperative that the library code not corrupt the collection by inserting an element of the wrong type.
The returned collection does not pass the hashCode and equals operations through to the backing collection, but relies on Object ‘s equals and hashCode methods. This is necessary to preserve the contracts of these operations in the case that the backing collection is a set or a list.
The returned collection will be serializable if the specified collection is serializable.
Since null is considered to be a value of any reference type, the returned collection permits insertion of null elements whenever the backing collection does.
checkedSet
A discussion of the use of dynamically typesafe views may be found in the documentation for the checkedCollection method.
The returned set will be serializable if the specified set is serializable.
Since null is considered to be a value of any reference type, the returned set permits insertion of null elements whenever the backing set does.
checkedSortedSet
A discussion of the use of dynamically typesafe views may be found in the documentation for the checkedCollection method.
The returned sorted set will be serializable if the specified sorted set is serializable.
Since null is considered to be a value of any reference type, the returned sorted set permits insertion of null elements whenever the backing sorted set does.
checkedList
A discussion of the use of dynamically typesafe views may be found in the documentation for the checkedCollection method.
The returned list will be serializable if the specified list is serializable.
Since null is considered to be a value of any reference type, the returned list permits insertion of null elements whenever the backing list does.
checkedMap
Assuming a map contains no incorrectly typed keys or values prior to the time a dynamically typesafe view is generated, and that all subsequent access to the map takes place through the view (or one of its collection views), it is guaranteed that the map cannot contain an incorrectly typed key or value.
A discussion of the use of dynamically typesafe views may be found in the documentation for the checkedCollection method.
The returned map will be serializable if the specified map is serializable.
Since null is considered to be a value of any reference type, the returned map permits insertion of null keys or values whenever the backing map does.
checkedSortedMap
Assuming a map contains no incorrectly typed keys or values prior to the time a dynamically typesafe view is generated, and that all subsequent access to the map takes place through the view (or one of its collection views), it is guaranteed that the map cannot contain an incorrectly typed key or value.
A discussion of the use of dynamically typesafe views may be found in the documentation for the checkedCollection method.
The returned map will be serializable if the specified map is serializable.
Since null is considered to be a value of any reference type, the returned map permits insertion of null keys or values whenever the backing map does.
emptyIterator
Implementations of this method are permitted, but not required, to return the same object from multiple invocations.
emptyListIterator
Implementations of this method are permitted, but not required, to return the same object from multiple invocations.
emptyEnumeration
Implementations of this method are permitted, but not required, to return the same object from multiple invocations.
emptySet
This example illustrates the type-safe way to obtain an empty set: Implementation note: Implementations of this method need not create a separate Set object for each call. Using this method is likely to have comparable cost to using the like-named field. (Unlike this method, the field does not provide type safety.)
emptyList
This example illustrates the type-safe way to obtain an empty list: Implementation note: Implementations of this method need not create a separate List object for each call. Using this method is likely to have comparable cost to using the like-named field. (Unlike this method, the field does not provide type safety.)
emptyMap
This example illustrates the type-safe way to obtain an empty set: Implementation note: Implementations of this method need not create a separate Map object for each call. Using this method is likely to have comparable cost to using the like-named field. (Unlike this method, the field does not provide type safety.)
singleton
singletonList
singletonMap
nCopies
reverseOrder
The returned comparator is serializable.
reverseOrder
The returned comparator is serializable (assuming the specified comparator is also serializable or null ).
enumeration
frequency
disjoint
Care must also be exercised when using collections that have restrictions on the elements that they may contain. Collection implementations are allowed to throw exceptions for any operation involving elements they deem ineligible. For absolute safety the specified collections should contain only elements which are eligible elements for both collections.
Note that it is permissible to pass the same collection in both parameters, in which case the method will return true if and only if the collection is empty.
addAll
When elements are specified individually, this method provides a convenient way to add a few elements to an existing collection:
newSetFromMap
Each method invocation on the set returned by this method results in exactly one method invocation on the backing map or its keySet view, with one exception. The addAll method is implemented as a sequence of put invocations on the backing map.
The specified map must be empty at the time this method is invoked, and should not be accessed directly after this method returns. These conditions are ensured if the map is created empty, passed directly to this method, and no reference to the map is retained, as illustrated in the following code fragment:
asLifoQueue
Each method invocation on the queue returned by this method results in exactly one method invocation on the backing deque, with one exception. The addAll method is implemented as a sequence of addFirst invocations on the backing deque.
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2020, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.