retainall java что делает
Метод ArrayList retainAll () в Java
Метод retainAll () ArrayList используется для удаления всех элементов списка массивов, которые не содержатся в указанной коллекции или сохраняют все совпадающие элементы в текущем экземпляре ArrayList, которые соответствуют всем элементам из списка Collection, переданных в качестве параметра методу.
Синтаксис:
Параметры: C — это коллекция, содержащая элементы, которые должны быть сохранены в списке.
Возвращаемое значение: метод возвращает логическое значение true, если список вообще изменяется в результате вызова else false.
Исключения:
Ниже программы используются для иллюстрации метода Java.util.ArrayList.retainAll ():
Программа 1: Передача коллекции ArrayList в качестве параметра методу.
// Java-код для иллюстрации метода retainAll ()
public static void main(String[] args)
// Создание пустого списка массивов
ArrayList bags = new ArrayList ();
// Добавить значения в список сумок.
// Создание другого списка массивов
ArrayList boxes = new ArrayList ();
// Добавить значения в список ящиков.
// Перед применением метода вывести оба списка
System.out.println( «Bags Contains :» + bags);
System.out.println( «Boxes Contains :» + boxes);
// Применяем метод retainAll () к ящикам, передающим сумки как параметр
// Отображение обоих списков после операции
System.out.println( «\nAfter Applying retainAll()» +
System.out.println( «Bags Contains :» + bags);
System.out.println( «Boxes Contains :» + boxes);
Программа 2: Передача Collection, отличного от ArrayList, в качестве параметра метода.
// Программа демонстрирует метод retainAll () с
// Коллекция отличается от ArrayList в качестве параметра метода
public static void main(String[] args)
// Создание пустого списка массивов
HashSet bags = new HashSet ();
// Добавить значения в пакетах Set.
// Создание другого пустого списка массивов
ArrayList boxes = new ArrayList ();
// Добавить значения в список ящиков.
// Перед применением метода выведите список и набор.
System.out.println( «Bags Contains :» + bags);
System.out.println( «Boxes Contains :» + boxes);
// Применяем метод retainAll () к ящикам, передающим сумки как параметр
// Отображение обоих списков после операции
System.out.println( «\nAfter Applying retainAll()» +
System.out.println( «Bags Contains :» + bags);
System.out.println( «Boxes Contains :» + boxes);
Программа 3: иллюстрирование ошибки, генерируемой методом retainAll ()
// Программа для иллюстрации ошибки, генерируемой методом retainAll ()
public static void main(String[] args)
// Создание пустого списка массивов
ArrayList list1 = null ;
/// Создание другого пустого списка массивов
ArrayList list2 = new ArrayList ();
// Добавить значения в список list2.
// Перед применением метода вывести оба списка
System.out.println( «list1 Contains :» + list1);
System.out.println( «list2 Contains :» + list2);
// Применяем метод retainAll () к list2, передавая list1 в качестве параметра
// Отображение обоих списков после операции
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.
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
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 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 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.