首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java集合总结系列2:Collection接口

Java集合总结系列2:Collection接口

作者头像
陈树义
发布2018-04-13 17:56:58
4430
发布2018-04-13 17:56:58
举报
文章被收录于专栏:陈树义陈树义陈树义

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<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 遍历时的接口,接口逻辑需要在具体的集合类中实现。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-05-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 操作类方法
  • 判断类方法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档