博客
关于我
Java集合总结系列2:Collection接口
阅读量:412 次
发布时间:2019-03-06

本文共 1286 字,大约阅读时间需要 4 分钟。

Collection 接口是 Java 集合类的一个根接口,Java 在 Collection 接口中定义了许多通用的数据操作类方法以及判断类方法。

通过查看 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
extends Iterable

而 Iterable<E> 接口定义如下:

/** * Implementing this interface allows an object to be the target of * the "foreach" statement. * * @param 
the type of elements returned by the iterator * * @since 1.5 */public interface Iterable
{ /** * Returns an iterator over a set of elements of type T. * * @return an Iterator. */ Iterator
iterator();}

也就是说如果一个对象实现了这个接口,那么这个对象就可以用 foreach 循环读取集合元素。

可以看到在 Iterator<T> 中有一个 Iterator<T> 接口,其定义如下:

public interface Iterator
{ boolean hasNext(); E next(); void remove();}

Iterator<T> 接口定义了进行 foreach 遍历时的接口,接口逻辑需要在具体的集合类中实现。

 

转载地址:http://ecakz.baihongyu.com/

你可能感兴趣的文章
Mysql:mysql 5.X 报错 ERROR 1193 (HY000): Unknown system variable ‘validate_password_length‘
查看>>
MySQL:MySQL执行一条SQL查询语句的执行过程
查看>>
Mysql:SQL性能分析
查看>>
mysql:SQL按时间查询方法总结
查看>>
MySQL:什么样的字段适合加索引?什么样的字段不适合加索引
查看>>
MySQL:判断逗号分隔的字符串中是否包含某个字符串
查看>>
MySQL:某个ip连接mysql失败次数过多,导致ip锁定
查看>>
MySQL:索引失效场景总结
查看>>
Mysql:避免重复的插入数据方法汇总
查看>>
MyS中的IF
查看>>
M_Map工具箱简介及地理图形绘制
查看>>
m_Orchestrate learning system---二十二、html代码如何变的容易
查看>>
M×N 形状 numpy.ndarray 的滑动窗口
查看>>
m个苹果放入n个盘子问题
查看>>
n = 3 , while n , continue
查看>>
n 叉树后序遍历转换为链表问题的深入探讨
查看>>
N!
查看>>
N-Gram的基本原理
查看>>
n1 c语言程序,全国青少年软件编程等级考试C语言经典程序题10道七
查看>>
Nacos Client常用配置
查看>>