1.Collection是Java集合框架中的一个接口,它代表一组对象的集合。它是Java集合框架中最基本的接口之一,定义了一组操作用于管理和操作集合中的元素。
Collection接口继承自java.lang.Iterable接口,因此它可以通过迭代器(Iterator)来遍历集合中的元素。它提供了一系列的方法,用于添加、删除、查询、遍历、判断元素是否存在等操作。
Java集合框架提供了多个Collection的实现类,如List、Set和Queue等。这些实现类都实现了Collection接口,并根据不同的需求提供了不同的特性和行为。
主要的Collection接口的子接口和实现类有:
- List:有序、可重复的集合,如ArrayList、LinkedList。
- Set:无序、不可重复的集合,如HashSet、TreeSet。
- Queue:一种先进先出(FIFO)的集合,如LinkedList、PriorityQueue。
- Deque:一种双端队列,可以在两端进行插入和删除操作,如ArrayDeque、LinkedList。
- Map:键值对的集合,如HashMap、TreeMap。
通过使用Collection接口及其实现类,我们可以方便地操作和管理数据集合,实现了数据的组织、存储和检索等功能。
2.迭代器的使用:对于一个ArrayList的遍历,我们说有很多种方法
(1)首先就是for循环遍历的方式
for (int i = 0; i < arrayList.size(); i++) {
System.out.print(arrayList.get(i)+" ");
}
System.out.println();
(2)for-each循环:
for(int x : arrayList) {
System.out.print(x+" ");
}
System.out.println();
(3)迭代器:
Iterator<Integer> it = arrayList.iterator();
while (it.hasNext()) {
System.out.print(it.next()+" ");
}
System.out.println();
(4)ListIterator遍历
ListIterator<Integer> it2 = arrayList.listIterator();
while (it2.hasNext()) {
System.out.print(it2.next()+" ");
}
System.out.println();
(5)从后向前遍历的接口,倒序输出
ListIterator<Integer> it3 =arrayList.listIterator(arrayList.size());
while (it3.hasPrevious()) {
System.out.print(it3.previous()+" ");
}
System.out.println();
}
打印结果: