这一章节我们来介绍一下Collection的常用方法。
我们下面以ArrayList为例。
package com.ray.ch14;
import java.util.ArrayList;
import java.util.Iterator;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> rtnList = new ArrayList<Integer>();
rtnList.add(1);// add方法
ArrayList<Integer> tempList = new ArrayList<Integer>();
tempList.add(2);
rtnList.addAll(tempList);// addAll方法
System.out.println(rtnList.contains(1));// contains方法
System.out.println(rtnList.containsAll(tempList));// containsAll方法
for (Iterator<Integer> 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<? extends E> 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<E> iterator() | 迭代器 |
boolean remove(Object o) | 移除对象 |
boolean removeAll(Collection<?> c) | 移除某Collection的所有元素 |
boolean retainAll(Collection<?> c) | 只保留两个Collection 的交集 |
Object[] toArray() | 返回包含此 collection 中所有元素的数组 |
<T> T[]toArray(T[] a) | 返回包含此 collection 中所有元素的数组;返回数组的运行时类型与指定数组的运行时类型相同 |
总结:这一章节主要介绍Collection的常用方法。
这一章节就到这里,谢谢。
-----------------------------------