Get to know java-15.2 collection's regular usage from scratch (2)-Watch out.

Source: Internet
Author: User

In the previous section we talked about the regular usage of collection. And the previous chapters, we introduced the AddAll method of collection, which we introduce to the attention point of this chapter.

Note that, in the regular usage, the basic is optional.

What is an optional operation?

Unfortunately, the method of operation is not set for all implementations. But only for the realization of a certain class set.

Like what:

Package Com.ray.ch15;import Java.util.arrays;import Java.util.collection;import Java.util.list;public class Test { public static void Test (list<string> List, String msg) {System.out.println ("---------" + msg + "--------"); list<string> sublist = list.sublist (1, 4); Collection<string> Collection = list;try {collection.retainall (sublist);} catch (Exception e) { System.out.println ("Retainall:" + E);}} public static void Main (string[] args) {list<string> list = Arrays.aslist ("1", "2", "3", "4", "5", "6"), Test (list, " Start1 ");}}

Output:

---------Start1--------
RetainAll:java.lang.UnsupportedOperationException


Why does it throw an exception?

Because Arrays.aslist is the lowest-level data structure of this method is an array, the array in Java is not modified. When Retainall this method to change the data structure inside the array, it is not agreed.

Assuming we output a bit more exception information above, we will locate the Abstractlist remove method. When it is called. Exceptions that are not supported will be thrown.

Public E Remove (int index) {throw new unsupportedoperationexception ();    }


Summary: This chapter focuses on the optional operation of collection's regular usage.


This chapter is here, thank you.

-----------------------------------

Folder




Get to know java-15.2 collection's regular usage from scratch (2)-Watch out.

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.