Common java-15.2 Collection methods (2)-notes
The previous section describes the common methods of Collection, and the addAll method of Collection. This section describes the precautions of Collection.
Note that in common methods, all operations are optional.
What is an optional operation?
Unfortunately, the operation method is not set for all implementations, but for a certain type of implementation.
For example:
package com.ray.ch15;import java.util.Arrays;import java.util.Collection;import java.util.List;public class Test {public static void test(List
list, String msg) {System.out.println("---------" + msg + "--------");List
subList = list.subList(1, 4);Collection
collection = list;try {collection.retainAll(subList);} catch (Exception e) {System.out.println("retainAll:" + e);}}public static void main(String[] args) {List
list = Arrays.asList("1", "2", "3", "4", "5", "6");test(list, "start1");}}
Output:
--------- Start1 --------
RetainAll: java. lang. UnsupportedOperationException
Why is the above exception thrown?
Because Arrays. the underlying data structure of the asList method is an array, which cannot be modified in java. When the retainAll method wants to modify the data structure in the array, it is not allowed.
If we output a little more exception information, we will locate the remove Method of AbstractList. When we call it, an unsupported exception will be thrown.
public E remove(int index) {throw new UnsupportedOperationException(); }
Summary: This section describes the optional operations of Collection methods.
This chapter is here. Thank you.