一、框架说明
- Collection接口:定义所有单列集合中共性的方法。
- List接口:有序的集合;允许存储重复的元素;有索引,可以使用普通的for循环遍历。
- Set集口:不允许存储重复元素;没有索引,不能使用普通的for循环遍历。
- TreeSet与HashSet是无序的集合;LinkedHashSet是有序的集合。
二、常用方法
集合架构中所有的类都可以使用的方法:
- public boolean add(E e):把给定的对象添加到当前集合中。
- public void clear():清空集合中所有的元素。
- public boolean remove(E e):把给定的对象在当前集合中删除。
- public boolean contains(E e):判断当前集合中是否包含给定的对象。
- public boolean isEmpty():判断当前集合是否为空。
- public int size():返回集合中元素的个数。
- public Object[] toArray():把集中的元素存储到数组中。
public static void main(String[] args) {
Collection<String> collection = new ArrayList<>();
/**
* public boolean add(E e):把给定的对象添加到当前集合中。
*/
collection.add("Hello");
collection.add("World");
collection.add("!!!!!");
/**
*public boolean remove(E e):把给定的对象在当前集合中删除。
*/
collection.remove("World");
/**
* public boolean contains(E e):判断当前集合中是否包含给定的对象。
* 包含返回true,不包含返回false
*/
boolean bool1 = collection.contains("World");
System.out.println(bool1); //返回false
/**
* public Object[] toArray():把集中的元素存储到数组中。
*/
Object[] strings=collection.toArray();
for (int i = 0; i < strings.length; i++) {
System.out.println(strings[i]);
}
/**
* public void clear():清空集合中所有的元素。
*/
collection.clear();
/**
* public boolean isEmpty():判断当前集合是否为空。
*/
boolean bool2= collection.isEmpty();
System.out.println(bool2); //返回true
}
三、Iterator迭代器
迭代器是Collection集合元素的通用获取方式,可以对集合进行遍历。
迭代器常用方法:
- boolean hasNex():判断集合中还有没有下一个元素。
- E next:取出集合中的下一个元素。
public static void main(String[] args) {
Collection<String> collection = new ArrayList<>();
collection.add("Hello");
collection.add("World");
collection.add("!!!!!");
Iterator<String> iterator= collection.iterator();
while(iterator.hasNext()){
String string= iterator.next();
System.out.println(string);
}
}
四、Iterator迭代器的实现原理
根据ArrayList的底层源码可能清晰地看到,迭代器的实现原理其实就是通过对底层elementData数组进行遍历获取数组中的对象元素。
/** ArrayList.java*/
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
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];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
五、集合的for each遍历
Collection接口继承了Iterable,Iterable接口中实现了默认方法forEach:
public interface Collection<E> extends Iterable<E>
public interface Iterable<T> {
/**
* Performs the given action for each element of the {@code Iterable}
* until all elements have been processed or the action throws an
* exception. Unless otherwise specified by the implementing class,
* actions are performed in the order of iteration (if an iteration order
* is specified). Exceptions thrown by the action are relayed to the
* caller.
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* for (T t : this)
* action.accept(t);
* }</pre>
*
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @since 1.8
*/
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
}
使用示例:
public static void main(String[] args) {
Collection<String> collection = new ArrayList<>();
collection.add("Hello");
collection.add("World");
collection.add("!!!!!");
for (String string:collection){
System.out.println(string);
}
}