從頭認識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的常用方法。
這一章節就到這裡,謝謝。