Java中的Collection接口

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();
}

打印结果:

  • 13
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值