Common java-15.2 Collection methods (2)-notes

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.