博客
关于我
Java集合总结系列2:Collection接口
阅读量:411 次
发布时间: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/

你可能感兴趣的文章
MySQL8,体验不一样的安装方式!
查看>>
MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
查看>>
Mysql: 对换(替换)两条记录的同一个字段值
查看>>
mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
查看>>
MYSQL:基础——3N范式的表结构设计
查看>>
MYSQL:基础——触发器
查看>>
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>
mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
查看>>
mysqldump 参数--lock-tables浅析
查看>>
mysqldump 导出中文乱码
查看>>
mysqldump 导出数据库中每张表的前n条
查看>>
mysqldump: Got error: 1044: Access denied for user ‘xx’@’xx’ to database ‘xx’ when using LOCK TABLES
查看>>
Mysqldump参数大全(参数来源于mysql5.5.19源码)
查看>>
mysqldump备份时忽略某些表
查看>>
mysqldump实现数据备份及灾难恢复
查看>>
mysqldump数据库备份无法进行操作只能查询 --single-transaction
查看>>
mysqldump的一些用法
查看>>
mysqli
查看>>
MySQLIntegrityConstraintViolationException异常处理
查看>>
mysqlreport分析工具详解
查看>>