retainall java что делает

Retainall java что делает

Интерфейс Set помещает дополнительные соглашения, вне наследованных от интерфейса Collection, по контрактам всех конструкторов и по контрактам add, методов equals И hashCode. Объявления для других наследованных методов также включаются здесь для удобства. (Спецификации, сопровождающие эти объявления, были адаптированы в соответствии с интерфейсом Set, но они не содержат дополнительных соглашений.)

Дополнительное соглашение на конструкторах, не удивительно, что все конструкторы должны создать набор, который не содержит двойных элементов (как определено выше).

У некоторых реализаций набора есть ограничения на элементы, которые они могут содержать. Например, некоторые реализации запрещают нулевые элементы, и у некоторых есть ограничения на типы их элементов. Попытка добавить неподходящий элемент выдает исключение непроверенное, обычно NullPointerException или ClassCastException. Попытка запросить присутствие неподходящего элемента может выдать исключение, или это может просто возвратить false; некоторые реализации покажут прежнее поведение, и некоторые покажут последнего. Более широко попытка работы на неподходящем элементе, завершение которого не привело бы к вставке неподходящего элемента в набор, может выдать исключение, или это может успешно выполниться в опции реализации. Такие исключения отмечаются как «дополнительные» в спецификации для этого интерфейса.

Этот интерфейс является элементом Платформы Наборов Java.

Сводка метода

Методы

Модификатор и ТипМетод и Описание
booleanadd(E e)

Деталь метода

размер

isEmpty

содержит

iterator

toArray

Возвращенный массив будет «безопасен» в этом, никакие ссылки на него не сохраняются этим набором. (Другими словами этот метод должен выделить новый массив, даже если этот набор поддерживается массивом). Вызывающая сторона таким образом свободна изменить возвращенный массив.

Этот метод действует как мост между основанными на массиве и основанными на наборе API.

toArray

Если этот набор помещается в указанный массив с комнатой, чтобы сэкономить (то есть, у массива есть больше элементов чем этот набор), элемент в массиве сразу после конца набора устанавливается в null. (Это полезно в определении длины этого набора, только если вызывающая сторона знает, что этот набор не содержит нулевых элементов.)

Если этот набор делает какие-либо гарантии относительно того, какой порядок его элементы возвращаются его iterator, этот метод должен возвратить элементы в том же самом порядке.

Как toArray() метод, этот метод действует как мост между основанными на массиве и основанными на наборе API. Далее, этот метод позволяет точное управление типом времени выполнения выходного массива, и, при определенных обстоятельствах, может использоваться, чтобы сохранить затраты выделения.

Предположите, что x является набором, который, как известно, содержал только строки. Следующий код может использоваться, чтобы вывести набор в недавно выделенный массив String: Отметьте, что toArray(new Object[0]) идентичен в функции toArray().

добавить

удалить

containsAll

addAll

retainAll

removeAll

очистить

равняется

хэш-код

Источник

Retainall 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

Methods

Modifier and TypeMethod and Description
booleanadd(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.

Источник

Retainall java что делает

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list 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 list 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

Methods

Modifier and TypeMethod and Description
booleanadd(E e)

Method Detail

isEmpty

contains

iterator

toArray

The returned array will be «safe» in that no references to it are maintained by this list. (In other words, this method must allocate a new array even if this list 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 the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following the end of the list is set to null. (This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements.)

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 list known to contain only strings. The following code can be used to dump the list into a newly allocated array of String: Note that toArray(new Object[0]) is identical in function to toArray().

Lists that support this operation may place limitations on what elements may be added to this list. In particular, some lists will refuse to add null elements, and others will impose restrictions on the type of elements that may be added. List classes should clearly specify in their documentation any restrictions on what elements may be added.

remove

containsAll

addAll

addAll

removeAll

retainAll

clear

equals

hashCode

remove

indexOf

lastIndexOf

listIterator

listIterator

subList

This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list: Similar idioms may be constructed for indexOf and lastIndexOf, and all of the algorithms in the Collections class can be applied to a subList.

The semantics of the list returned by this method become undefined if the backing list (i.e., this list) is structurally modified in any way other than via the returned list. (Structural modifications are those that change the size of this list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)

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.

Источник

Retainall java что делает

Bags or multisets (unordered collections that may contain duplicate elements) should implement this interface directly.

All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its subinterfaces) should provide two «standard» constructors: a void (no arguments) constructor, which creates an empty collection, and a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument. In effect, the latter constructor allows the user to copy any collection, producing an equivalent collection of the desired implementation type. There is no way to enforce this convention (as interfaces cannot contain constructors) but all of the general-purpose Collection implementations in the Java platform libraries comply.

The «destructive» methods contained in this interface, that is, the methods that modify the collection on which they operate, are specified to throw UnsupportedOperationException if this collection does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException if the invocation would have no effect on the collection. For example, invoking the addAll(Collection) method on an unmodifiable collection may, but is not required to, throw the exception if the collection to be added is empty.

It is up to each collection to determine its own synchronization policy. In the absence of a stronger guarantee by the implementation, undefined behavior may result from the invocation of any method on a collection that is being mutated by another thread; this includes direct invocations, passing the collection to a method that might perform invocations, and using an existing iterator to examine the collection.

This interface is a member of the Java Collections Framework.

Источник

Retainall java что делает

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.

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be «wrapped» using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *