從頭認識java-15.2 Collection的經常用法(2)-注意點

來源:互聯網
上載者:User

標籤:ati   details   mod   常用   資料   post   tail   try   print   

上一章節我們講述了Collection的經常用法。還有之前的章節我們介紹了Collection的addAll方法,這一章節我們介紹一下它的注意點。

注意點就是,在經常用法裡面,基本都是可選操作。

什麼是可選操作?

可惜操作的方法不是為全部的實現而設定的。而僅僅是為某一類的實現而設定的。

比如:

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");}}

輸出:

---------start1--------
retainAll:java.lang.UnsupportedOperationException


為什麼上面會拋異常呢?

由於Arrays.asList這種方法最底層的資料結構是一個數組,數組在java裡面是不可改動的。當retainAll這種方法想改動數組裡面的資料結構時,它是不被同意的。

假設我們上面輸出多一點異常資訊,我們將會定位到AbstractList的remove方法。當調用它的時候。將會拋不被支援的異常。

public E remove(int index) {throw new UnsupportedOperationException();    }


總結:這一章節主要介紹了Collection的經常用法的可選操作。


這一章節就到這裡,謝謝。

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

檔案夾




從頭認識java-15.2 Collection的經常用法(2)-注意點

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.