Java Collection

337 阅读2分钟

单列集合顶层接口 Collection

Collection是单列集合的祖宗接口,它的功能是全部单列集合都可以继承使用的

方法名说明
public boolean add(E e)把给定的对象添加到当前集合中
public void clear()清空集合中所有的元素
public boolean remove(E e)把给定的对象在当前集合中删除
public boolean contains(Object obj)判断当前集合中是否包含给定的对象
public boolean isEmpty()判断当前集合是否为空
public int size()返回集合中元素的个数/集合的长度
  • public boolean add(E e)方法细节

    • 如果我们要往List系列集合中添加数据,那么方法永远返回true,因为List系列是允许元素重复的
    • 如果我们要往Set系列集合中添加数据
      • 如果当前要添加的元素不存在,方法返回true,表示添加成功
      • 如果当前要添加的元素已经存在,方法返回false,表示添加失败,因为Set系列的集合不允许重复
  • public boolean remove(E e)方法细节

    • 因为Collection里面定义的是共性的方法,所以此时不能通过索引进行删除,只能通过元素的对象进行删除
    • 方法会有一个布尔类型的返回值,删除成功返回true,删除失败返回false,如果要删除的元素不存在,就会删除失败
  • public boolean contains(Object obj)方法细节

    • 底层是依赖equals方法进行判断是否存在的
    • 所以如果集合中存储的是自定义对象,也想通过contains方法来判断是否包含,那么在javabean类中,一定要重写equals方法
//ArrayList类中重写的contains方法
public boolean contains(Object o) {
    return indexOf(o) >= 0;
}

public int indexOf(Object o) {
    return indexOfRange(o, 0, size);
}

int indexOfRange(Object o, int start, int end) {
    Object[] es = elementData;
    if (o == null) {
        for (int i = start; i < end; i++) {
            if (es[i] == null) {
                return i;
            }
        }
    } else {
        for (int i = start; i < end; i++) {
            if (o.equals(es[i])) {
                return i;
            }
        }
    }
    return -1;
}
  • public boolean isEmpty()底层原理
    • 判断集合的长度是否为零
//ArrayList中重写的isEmpty方法
public boolean isEmpty() {
    return size == 0;
}