Java集合类总结 (一)

集合类中的基本接口

集合类中最基础的接口是Collection:

public interface Collection<E>
{
    boolean add(E element);
    Iterator<E> iterator();
}

add方法加一个元素到集合中,如果改变了集合则返回true,如果集合未改变则返回false。例如,如果试图向set中加入一个已经存在其中的对象是,此add接口将返回false,因为set不允许加入重复的对象,故你没有改变集合。

iterator方法返回用来遍历集合的对象,其实现了接口Iterator,看一下Iterator的定义:

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

“for each”语法可以用于所有实现了Iterable接口的对象,其Iterable接口也只是包括了一个返回实现了Iterator对象的方法:

public interface Iterable<E>
{
    Iterator<E> iterator();
}

Collection接口扩展了Iterable接口,所以所有Collection都可以使用for each语法遍历。

 

Iterator接口方法介绍

关于Iterator接口的next方法,当你调用一次next方法后,Iterator会跳到下一个元素的后面,并返回所跳过元素的引用,如下图:

关于Iterator接口的remove方法,它会移除上一次调用next所返回的元素,也就是会移除刚刚Iterator跳过的那个元素。

移除collection中首个元素:

Iterator<String> it = c.iterator();
it.next(); //Skip over the first element
it.remove(); // now remove it

可见,next与remove方法是有依赖关系的。如果从没有调用next就直接调用remove方法,那就是非法操作,并会抛出IllegalStateException异常。
并且连续调用两次remove,第二次调用也是非法的:

it.remove();
it.remove(); //ERROR!!

你必须在每一次调用remove之前调用next:

it.remove();
it.next();
it.remove(); // OK

 

实现自己的collection类

由于Collection接口定义了很多的方法,如果自己要实现它,会重复做很多工作,Java类库准备了很多的抽象类,这些类实现了Collection接口,并实现了部分常用的公用的方法,所以当你去实现自己的collection类时,不需要再去重新造轮子了,只需要继承这些抽象类,并覆盖那些你需要自定义的方法即可。

public abstract class AbstractCollection<E> implements Collection<E>
{
   . . .
       public abstract Iterator<E> iterator();
       public boolean contains(Object obj)
       {
          for (E element : this) // calls iterator()         
          {    
            if (element.equals(obj))
                return = true;
          }
           return false;
       }
   . . .
}

如上面的抽象类实现了常用方法contains。

原文地址:https://www.cnblogs.com/liupengblog/p/5181789.html