面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,Java就提供了集合类。
由于需求不同,Java提供了不同的集合类。虽然这多个集合类的数据结构不同,但它们都要提供存储和遍历功能。我们把它们的共性不断向上提取,最终形成了集合的继承体系结构。
Collection | – List | – ArrayList| – Vector| – LinkedList | – Set | – HashSet| – TreeSetCollection 层次结构中的根接口。Collection 表示一组对象,这些对象也称为 collection 的元素。一些 collection 允许有重复的元素,而另一些则不允许。一些 collection 是有序的,而另一些则是无序的。
添加功能 boolean add(Object obj):添加一个元素 boolean addAll(Collection c):添加一个集合的元素
删除功能 void clear():移除所有元素 boolean remove(Object obj):移除一个元素 boolean removeAll(Collection c):移除一个集合的元素
判断功能 boolean contains(Object obj) 判断集合中是否包含指定的元素 boolean containsALL(Collection c)) 判断集合中是否包含指定的集合元素,包含指定集合所有元素才返回true boolean isEmpty():判断集合是否为空
获取功能 Iterator iterator():见下一个标题处。
长度功能 int size():元素的个数 面试题:数组有没有length()方法?字符串有没有length()方法?集合有没有length()方法?(没有;有;没有)
交集功能 boolean retainAll(Collection c) 两个集合都有的元素。返回值为true代表原集合元素发生改变,否则返回false。
把集合转换为数组 Object[] toArray()
public interface Iterator 迭代器是集合获取元素的方式。迭代器是依赖于集合存在的。 Collection的成员方法:Iterator iterator()
1. Object next():获取元素,并移动到下一个位置。 可能抛出的异常:NoSuchElementException,代表没有下一个元素,已经找到最后了。所以可以在每次获取时,先判断是否有下一个元素。
// 创建集合对象 Collection c = new ArrayList(); c.add("hello"); c.add("world"); c.add("java"); // Iterator iterator():迭代器,集合的专用遍历方式 Iterator it = c.iterator(); // 实际返回的肯定是子类对象,这里是多态 while (it.hasNext()) { // System.out.println(it.next()); String s = (String) it.next(); System.out.println(s); }2. boolean hasNext() 如果仍有元素可以迭代,则返回 true。(换句话说,如果 next 返回了元素而不是抛出异常,则返回 true)。
Iterator源码如下:
public interface Inteator { boolean hasNext(); Object next(); } public interface Iterable { Iterator iterator(); } public interface Collection extends Iterable { Iterator iterator(); } public interface List extends Collection { Iterator iterator(); } // 具体的子类中以内部类的方式实现了iterator()方法。 public class ArrayList implements List { public Iterator iterator() { return new Itr(); } private class Itr implements Iterator { public boolean hasNext() {} public Object next(){} } } Collection c = new ArrayList(); c.add("hello"); c.add("world"); c.add("java"); Iterator it = c.iterator(); //new Itr(); while(it.hasNext()) { String s = (String)it.next(); System.out.println(s); }