Что такое set java
Что такое set java
The Set interface places additional stipulations, beyond those inherited from the Collection interface, on the contracts of all constructors and on the contracts of the add, equals and hashCode methods. Declarations for other inherited methods are also included here for convenience. (The specifications accompanying these declarations have been tailored to the Set interface, but they do not contain any additional stipulations.)
The additional stipulation on constructors is, not surprisingly, that all constructors must create a set that contains no duplicate elements (as defined above).
Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.
Some set implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the set may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.
This interface is a member of the Java Collections Framework.
Множества: Set, HashSet, LinkedHashSet, TreeSet
HashSet, TreeSet и LinkedHashSet относятся к семейству Set. В множествах Set каждый элемент хранится только в одном экземпляре, а разные реализации Set используют разный порядок хранения элементов. В HashSet порядок элементов определяется по сложному алгоритму. Если порядок хранения для вас важен, используйте контейнер TreeSet, в котором объекты хранятся отсортированными по возрастанию в порядке сравнения или LinkedHashSet с хранением элементов в порядке добавления.
Множества часто используются для проверки принадлежности, чтобы вы могли легко проверить, принадлежит ли объект заданному множеству, поэтому на практике обычно выбирается реализация HashSet, оптимизированная для быстрого поиска.
В Android 11 (R) обещают добавить несколько перегруженных версий метода of(), которые являются частью Java 8.
HashSet
Название Hash. происходит от понятия хэш-функция. Хэш-функция — это функция, сужающая множество значений объекта до некоторого подмножества целых чисел. Класс Object имеет метод hashCode(), который используется классом HashSet для эффективного размещения объектов, заносимых в коллекцию. В классах объектов, заносимых в HashSet, этот метод должен быть переопределен (override).
Имеет два основных конструктора (аналогично ArrayList):
Методы
Методы аналогичны методам ArrayList за исключением того, что метод add(Object o) добавляет объект в множество только в том случае, если его там нет. Возвращаемое методом значение — true, если объект добавлен, и false, если нет.
Итак, создадим множество стран.
Нажав на кнопку, вы получите результат Размер HashSet = 4.
Даже если вы попытаетесь схитрить и дополнительно вставить строку countryHashSet.add(«Кот-Д’Ивуар»); после России, то всё-равно размер останется прежним.
Убедиться в этом можно, если вызвать метод iterator(), который позволяет получить всё множество элементов:
Несмотря на наше упрямство, мы видим только четыре добавленных элемента.
Стоит отметить, что порядок добавления стран во множество будет непредсказуемым. HashSet использует хэширование для ускорения выборки. Если вам нужно, чтобы результат был отсортирован, то пользуйтесь TreeSet.
Преобразовать в массив и вывести в ListView
Продолжим опыты. Поработаем теперь с числами.
Здесь мы ещё раз убеждаемся, что повторное добавление числа не происходит. В цикле случайным образом выбирается число от 0 до 9 тысячу раз. Естественно, многие числа должны были повториться при таком сценарии, но во множество каждое число попадёт один раз.
При этом данные не сортируются, так как расположены как попало.
Специально для Android был разработан новый класс ArraySet, который более эффективен.
LinkedHashSet
Класс LinkedHashSet расширяет класс HashSet, не добавляя никаких новых методов. Класс поддерживает связный список элементов набора в том порядке, в котором они вставлялись. Это позволяет организовать упорядоченную итерацию вставки в набор.
TreeSet
Переделанный пример для вывода случайных чисел в отсортированном порядке. HashSet не может гарантировать, что данные будут отсортированы, так как работает по другому алгоритму. Если сортировка для вас важна, то используйте TreeSet.
Со строками это выглядит нагляднее:
Названия стран выведутся в алфавитном порядке.
Класс TreeSet создаёт коллекцию, которая для хранения элементов применяет дерево. Объекты сохраняются в отсортированном порядке по возрастанию.
SortedSet
В примере с TreeSet использовался интерфейс SortedSet, который позволяет сортировать элементы множества. По умолчанию сортировка производится привычным способом, но можно изменить это поведение через интерфейс Comparable.
Кроме стандартных методов Set у интерфейса есть свои методы.
The Set Interface
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. Two Set instances are equal if they contain the same elements.
Or, if using JDK 8 or later, you could easily collect into a Set using aggregate operations:
Here’s a slightly longer example that accumulates a Collection of names into a TreeSet :
And the following is a minor variant of the first idiom that preserves the order of the original collection while removing duplicate elements:
The following is a generic method that encapsulates the preceding idiom, returning a Set of the same generic type as the one passed.
Set Interface Basic Operations
The following program prints out all distinct words in its argument list. Two versions of this program are provided. The first uses JDK 8 aggregate operations. The second uses the for-each construct.
Using JDK 8 Aggregate Operations:
Using the for-each Construct:
Now run either version of the program.
The following output is produced:
Note that the code always refers to the Collection by its interface type ( Set ) rather than by its implementation type. This is a strongly recommended programming practice because it gives you the flexibility to change implementations merely by changing the constructor. If either of the variables used to store a collection or the parameters used to pass it around are declared to be of the Collection ‘s implementation type rather than its interface type, all such variables and parameters must be changed in order to change its implementation type.
Furthermore, there’s no guarantee that the resulting program will work. If the program uses any nonstandard operations present in the original implementation type but not in the new one, the program will fail. Referring to collections only by their interface prevents you from using any nonstandard operations.
Set Interface Bulk Operations
Bulk operations are particularly well suited to Set s; when applied, they perform standard set-algebraic operations. Suppose s1 and s2 are sets. Here’s what bulk operations do:
To calculate the union, intersection, or set difference of two sets nondestructively (without modifying either set), the caller must copy one set before calling the appropriate bulk operation. The following are the resulting idioms.
Let’s revisit the FindDups program. Suppose you want to know which words in the argument list occur only once and which occur more than once, but you do not want any duplicates printed out repeatedly. This effect can be achieved by generating two sets one containing every word in the argument list and the other containing only the duplicates. The words that occur only once are the set difference of these two sets, which we know how to compute. Here’s how the resulting program looks.
When run with the same argument list used earlier ( i came i saw i left ), the program yields the following output.
A less common set-algebraic operation is the symmetric set difference the set of elements contained in either of two specified sets but not in both. The following code calculates the symmetric set difference of two sets nondestructively.
Set Interface Array Operations
Что такое set java
The Set interface places additional stipulations, beyond those inherited from the Collection interface, on the contracts of all constructors and on the contracts of the add, equals and hashCode methods. Declarations for other inherited methods are also included here for convenience. (The specifications accompanying these declarations have been tailored to the Set interface, but they do not contain any additional stipulations.)
The additional stipulation on constructors is, not surprisingly, that all constructors must create a set that contains no duplicate elements (as defined above).
Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.
Some set implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the set may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.
This interface is a member of the Java Collections Framework.
Method Summary
Modifier and Type | Method and Description |
---|---|
boolean | add(E e) |
Method Detail
isEmpty
contains
iterator
toArray
The returned array will be «safe» in that no references to it are maintained by this set. (In other words, this method must allocate a new array even if this set is backed by an array). The caller is thus free to modify the returned array.
This method acts as bridge between array-based and collection-based APIs.
toArray
If this set fits in the specified array with room to spare (i.e., the array has more elements than this set), the element in the array immediately following the end of the set is set to null. (This is useful in determining the length of this set only if the caller knows that this set does not contain any null elements.)
If this set makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.
Like the toArray() method, this method acts as bridge between array-based and collection-based APIs. Further, this method allows precise control over the runtime type of the output array, and may, under certain circumstances, be used to save allocation costs.
Suppose x is a set known to contain only strings. The following code can be used to dump the set into a newly allocated array of String: Note that toArray(new Object[0]) is identical in function to toArray().
remove
containsAll
addAll
retainAll
removeAll
clear
equals
hashCode
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.
Коллекция HashSet
1. Контейнеры и коллекции
Контейнерами или коллекциями называют классы, которые позволяют хранить и обрабатывать много объектов сразу. Вы уже знаете две разновидности контейнеров — массивы и списки.
В Java есть несколько десятков коллекций, каждая из которых хранит элементы своим специфическим способом. Вот некоторые из них:
Тип коллекции | Класс | Описание |
---|---|---|
Список | ||
Связный список | ||
Вектор | ||
Стэк (стопка) | ||
Множество | ||
Очередь | ||
Карта/Словарь |
Поэтому коллекции разделились на коллекции в широком смысле и коллекции в узком смысле (только те, которые реализуют интерфейс Collection ).
2. Коллекция HashSet
Создать объект типа HashSet можно с помощью команды вида:
У класса HashSet есть такие методы:
Пример использования множества.
Давайте напишем программу, которая прощается с пользователем, если он с ней поздоровался: если пользователь сказал привет. Для большего интереса «привет» можно будет говорить на нескольких языках.
Заносим в set приветствия на разных языках.
Вводим с консоли слово,
если это слово есть в нашем множестве приветствий, то прощаемся (по-белорусски).
3. Множество
Коллекция Set создана для хранения множества элементов. Поэтому ее так и называют Set (множество). У этой коллекции есть три особенности.
Операции над множеством
С множеством можно делать только три операции: добавлять элементы во множество, удалять элементы из множества и проверять, есть ли во множестве определенный элемент. Все.
Отсутствие порядка
У элементов этой коллекции нет номеров. Нельзя получить элемент по его индексу или записать значение в коллекцию по определенному индексу. Методов get() и set() у множества нет.
Уникальность элементов
Все элементы множества уникальны. В отличие от списка, в множестве один элемент может быть только раз. Объект или находится во множестве, или нет: третьего не дано. Нельзя во «множество цветов» трижды добавить «черный цвет». Он там либо есть, либо его нет.
Поиск элементов
4. Сравнение коллекций: List vs Set
Давайте попробуем сравнить Список и Множество на примере детских игрушек.
Коллекция List (Список) похожа на набор игрушек в детской комнате, стоящих возле стены. Можно добавить игрушку в конец списка. Можно вставить и в середину, если очень нужно (но часть игрушек придется передвинуть).
У каждой игрушки есть порядковый номер. Можно взять игрушку по ее номеру или заменить игрушку номер 7 на игрушку номер 13. Можно удалить из списка игрушку номер 4. Ну и наконец, можно узнать количество всех игрушек в списке.
Коллекция Set (Множество) больше похожа на игрушки, сброшенные в кучу. В кучу можно добавить игрушку, можно удалить игрушку из кучи. Но фиксированного номера у таких игрушек нет.
Или допустим, вы выбираете ребенку игрушку на день рождения. Тогда вы в первую очередь думаете, есть у него такая игрушка или нет. Тогда все игрушки, которые у него есть, образуют множество игрушек, которые вы решили не покупать.
С этой точки зрения порядок игрушек в наборе «уже есть» не играет роли, как и наличие у именинника двух одинаковых игрушек. Вас интересуют не сами игрушки и их количество, а игрушки как набор неких уникальных объектов.