Collection子接口
Collection 接口也是java集合类中一个父类接口,Collection 子接口常用的有List,Set等。。。
因为List与Set的子类都会实现Collection接口,因此我们可以通过统一的迭代操作:
public static void doSomething(Collection collection){
Iterator iterator = collection.iterator();
while(iterator.hasNext()){
Object obj = iterator.next();
// do somethong with obj here
}
}
集合的添加和删除
不管集合子类内部如何实现添加和删除操作,我们只需要简单调用add()与remove()方法即可
String element = "an element";
Collection collection = new HashSet();
boolean added = collection.add(element);
boolean removed = collection.remove(element);
除了添加和删除单个元素外,Collection接口中还有添加和删除一个集合的操作:
Set set = new HashSet();
List list = new ArrayList();
Collection collection = new HashSet();
collection.addAll(set);
collection.addAll(list);
collection.removeAll(set);
collection.removeAll(list);
判断元素或集合是否存在与集合中
Collection collection = new HashSet();
boolean contained = collection.contains("an element");
Collection elements = new HashSet();
boolean containedAll = collection.containsAll(elements);
获取集合中元素数量
int numberOfElements = collection.size();
迭代操作
// iterator方式
Collection collection = new HashSet();
//... add elements to the collection
Iterator iterator = collection.iterator();
while(iterator.hasNext()){
Object object = iterator.next();
//do something to object;
}
// for-loop方式
Collection collection = new HashSet();
//... add elements to the collection
for(Object object : collection) {
//do something to object;
}