概述
1、集合类存放于 java.util 包中。
2、集合类存放的都是对象的引用,而非对象本身,出于表达上的便利,我们称集合中的对象就是指集合中对象的引用(reference)。
3、集合类型主要有 3 种:Set(集)、List(列表)和 Map(映射)。
通俗的说,集合就是一个放数据的容器,准确的说是存放数据对象引用的容器。
java 集合层次结构
说说快速失败机制 “fail-fast”?
Java集合的一种错误检测机制,当多个线程对集合进行结构上的改变的操作时,有可能会产生 fail-fast 机制。例如:假设存在两个线程(线程1、线程2),线程1通过 Iterator 在遍历集合A中的元素,在某个时候线程2修改了集合A的结构(是结构上面的修改,而不是简单的修改集合元素的内容),那么这个时候程序就会抛出 ConcurrentModificationException 异常,从而产生 fail-fast 机制。
其实关键就是这个 modCount 变量,就是在调用 add()、remove() 等方法时,会增加modCount 的值,每当迭代器使用 next() 遍历下一个元素之前,都会检测 modCount 变量是否为 expectedmodCount 值,是的话就返回遍历;否则抛出异常,终止遍历。
private class Itr implements Iterator<E> {
int expectedModCount = modCount;
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
// 检测 modCount 变量是否为 expectedmodCount 值
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
讲一讲迭代器Iterator遍历?
Iterator 接口也是Java集合框架的成员,主要用于遍历,常用方法:
boolean hasNext():返回集合里的下一个元素,若有为true,反之为false;
E next():(1)指针下移 (2)返回集合里的下一个元素;
void remove():删除集合里上一次next方法返回的元素;
Iterator 接口提供遍历任何 Collection 的接口。我们可以从一个 Collection 中使用迭代器方法来获取迭代器实例。迭代器取代了Java 集合框架中的 Enumeration,迭代器允许调用者在迭代过程中移除元素。Iterator 的特点是只能单向遍历,但是更加安全,因为它可以确保,在当前遍历的集合元素被更改的时候,就会抛出 ConcurrentModificationException 异常。
public interface Iterator<E> {
/**
* Returns true if the iteration has more elements.
*/
boolean hasNext();
/**
* Returns the next element in the iteration.
*/
E next();
/**
* Removes from the underlying collection the last element returned
* by this iterator.
*/
default void remove() {
throw new UnsupportedOperationException("remove");
}
}