Collection是所有单列集合的父接口,因此在Collection中定义了单列集合(List和Set)通用的一些方法,这些方法可用于操作所有的单列集合。方法如下:
-
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 Object[] toArray()
: 把集合中的元素,存储到数组中
Iterator接口
public Iterator iterator()
: 获取集合对应的迭代器,用来遍历集合中的元素的。
Iterator接口的常用方法如下:
-
public E next()
:返回迭代的下一个元素。 -
public boolean hasNext()
:如果仍有元素可以迭代,则返回 true。
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("蔡依林",20));
list.add(new Person("刘知珉",22));
//迭代
Iterator<Person> it = list.iterator();
while(it.hasNext()){
Person p = it.next();
System.out.println(p.getName()+" "+p.getAge());
}
注意:
-
在进行集合元素获取时,如果集合中已经没有元素了,还继续使用迭代器的next方法,将会抛出java.util.NoSuchElementException没有集合元素异常。
-
在进行集合元素获取时,如果添加或移除集合中的元素 , 将无法继续迭代 , 将会抛出ConcurrentModificationException并发修改异常.
增强for
增强for循环(也称for each循环)是JDK1.5以后出来的一个高级for循环,专门用来遍历数组和集合的。它的内部原理其实是个Iterator迭代器,所以在遍历的过程中,不能对集合中的元素进行增删操作。
格式:
for(数据类型 变量名:集合或数组){
}
示例:
int[] arr = {3,8,2,5,0};
//遍历数组
for(int num:arr){
System.out.println(num);
}
//遍历集合
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("蔡依林",20));
list.add(new Person("刘知珉",22));
for(Person p :list){
System.out.println(p.getName()+" "+p.getAge());
}