Java集合总结系列2:Collection接口
2016-05-04 11:01
351 查看
Collection 接口是 Java 集合类的一个根接口,Java 在 Collection 接口中定义了许多通用的数据操作类方法以及判断类方法。
通过查看 API 文档或源码的方式,我们可以了解到 Collection 接口中的方法大致分为两类:操作类方法和判断类方法。
boolean addAll(Collection<? extends E> c);
boolean remove(Object o);
boolean removeAll(Collection<?> c);
void clear();
boolean retainAll(Collection<?> c); 仅仅保存集合c中的元素
Iterator<E> iterator();
boolean containsAll(Collection<?> c);
boolean isEmpty();
int size();
Collection 接口中定义的这些方法都是 List、Set、Queue 这3种数据结构所共有的一些行为,因此适合作为父级接口的方法。
查看 Java 源码我们可以看到 Collection 接口还继承了 Iterable<E> 接口:
而 Iterable<E> 接口定义如下:
也就是说如果一个对象实现了这个接口,那么这个对象就可以用 foreach 循环读取集合元素。
可以看到在 Iterator<T> 中有一个 Iterator<T> 接口,其定义如下:
Iterator<T> 接口定义了进行 foreach 遍历时的接口,接口逻辑需要在具体的集合类中实现。
通过查看 API 文档或源码的方式,我们可以了解到 Collection 接口中的方法大致分为两类:操作类方法和判断类方法。
操作类方法
boolean add(E e);boolean addAll(Collection<? extends E> c);
boolean remove(Object o);
boolean removeAll(Collection<?> c);
void clear();
boolean retainAll(Collection<?> c); 仅仅保存集合c中的元素
Iterator<E> iterator();
判断类方法
boolean contains(Object o);boolean containsAll(Collection<?> c);
boolean isEmpty();
int size();
Collection 接口中定义的这些方法都是 List、Set、Queue 这3种数据结构所共有的一些行为,因此适合作为父级接口的方法。
查看 Java 源码我们可以看到 Collection 接口还继承了 Iterable<E> 接口:
public interface Collection<E> extends Iterable<E>
而 Iterable<E> 接口定义如下:
/** * Implementing this interface allows an object to be the target of * the "foreach" statement. * * @param <T> the type of elements returned by the iterator * * @since 1.5 */ public interface Iterable<T> { /** * Returns an iterator over a set of elements of type T. * * @return an Iterator. */ Iterator<T> iterator(); }
也就是说如果一个对象实现了这个接口,那么这个对象就可以用 foreach 循环读取集合元素。
可以看到在 Iterator<T> 中有一个 Iterator<T> 接口,其定义如下:
public interface Iterator<E> { boolean hasNext(); E next(); void remove(); }
Iterator<T> 接口定义了进行 foreach 遍历时的接口,接口逻辑需要在具体的集合类中实现。
相关文章推荐
- Spring中配置和读取多个Properties文件
- Spring scope属性详解
- java基础の重载和重写区别和联系
- JAVA中创建ZIP文件,并向ZIP文件中写入并读取条目和数据
- (转载)JavaWeb学习总结(五十)——文件上传和下载
- DWR中各种java方法的调用
- Struts2单个与多个文件上传之一
- java基础のsuper和this区别和联系
- Eclipse WEB项目更改项目名
- 蓝桥杯 六角幻方 2014年JavaB组决赛试题
- java 基础
- Java线程:概念与原理
- java io的笔记
- Java 数组
- spring整合cxf 客户端+服务端
- Java实现常见排序算法
- Windows 使用Eclipse配置连接hadoop,编译运行MapReduce --本地调试WordCount
- java的命名规则(转载)
- Eclipse中配置Maven build打包
- Java项目中调用Kettle转换