從頭認識java-15.2 Collection的常用方法

來源:互聯網
上載者:User

從頭認識java-15.2 Collection的常用方法

這一章節我們來介紹一下Collection的常用方法。

我們下面以ArrayList為例。

package com.ray.ch14;import java.util.ArrayList;import java.util.Iterator;public class Test {public static void main(String[] args) {ArrayList rtnList = new ArrayList();rtnList.add(1);// add方法ArrayList tempList = new ArrayList();tempList.add(2);rtnList.addAll(tempList);// addAll方法System.out.println(rtnList.contains(1));// contains方法System.out.println(rtnList.containsAll(tempList));// containsAll方法for (Iterator iterator = tempList.iterator(); iterator.hasNext();) {// Iterator迭代器Integer item = (Integer) iterator.next();System.out.println(item);}System.out.println(rtnList.size());// size方法rtnList.retainAll(tempList);// retainAll方法rtnList.add(1);// add方法rtnList.remove(1);// remove方法rtnList.removeAll(tempList);// removeAll方法}}

輸出:

true
true
2
2

Collection的常用操作

方法

意義

boolean add(E e)

添加指定的元素

boolean addAll(Collection c)

將指定collection 中的所有元素都添加到新的collection 中

void clear()

移除所有元素

boolean contains(Object o)

檢測是否包含指定的元素,如果真返回true,反之返回false

boolean containsAll(Collection c)

檢測是否包含某Collection的所有元素,如果真返回true,反之返回false

boolean equals(Object o)

對比指定的對象

int hashCode()

返回雜湊碼值

boolean isEmpty()

是否為空白

Iterator iterator()

迭代器

boolean remove(Object o)

移除對象

boolean removeAll(Collection c)

移除某Collection的所有元素

boolean retainAll(Collection c)

只保留兩個Collection 的交集

Object[] toArray()

返回包含此 collection 中所有元素的數組

T[]toArray(T[] a)

返回包含此 collection 中所有元素的數組;返回數組的運行時類型與指定數組的運行時類型相同

總結:這一章節主要介紹Collection的常用方法。

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.