Iterable
1.在collection集合体系中的位置及作用
处于顶层,作为最基础的接口。
实现此接口,可以通过iterator迭代器遍历整个集合。
2.Iterable接口中的方法:
(1)forEach():对集合使用forEach()进行遍历
public static void testForEach() {
List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4));
list.forEach(System.out::println);
}
(2)Iterator():返回类型为T元素的迭代器
//获取迭代器
Iterator it = list.iterator();
//输出集合中的第一个元素
System.out.println(it.next());
//让迭代器it逐个返回集合中的所有元素
while (it.hasNext()) {
System.out.println(it.next());
}
//删除
while (it.hasNext()) {
Integer i = (Integer) it.next();
it.remove();
}
Collection接口
1.除去Iterable接口,它是集合体系中的最底层接口,所有其实现类,子接口都必须实现或继承它的方法。同时该接口规范了不管是线性表(数组和链表)、队列、Hash和树结构集合子类所要实现的共性方法。所有其实现类,在此约束和接口进行实现。
2.常见方法:
Collection<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4));
// list.forEach(System.out::print);
//添加元素
list.add(5);
//判断集合是否没有任何元素
System.out.println(list.isEmpty());//false
//删除
list.remove(5);
System.out.println(list.size());//4
//返回一个装有所有集合中元素的数组
Object[] array = list.toArray();
System.out.println(Arrays.toString(array));//[1,2,3,4]
//清空
list.clear();
List接口
1.常见方法:
List<Integer> list = new ArrayList<>();
//尾插
list.add(1);
//将元素插到index位置
list.add(1,2);//(index,element)
//尾插c中的元素(Collection<? extends E> c)
Collection<Integer> c = new ArrayList<>(Arrays.asList(8,9,6));
list.addAll(c);
//删除index位置的元素
list.remove(0);
//删除遇到的第一个对象
//删除集合
list.removeAll(c);
list.forEach(System.out::println);
//获取下标index位置的元素
int num = list.get(1);
//将下标index位置元素设置为element
list.set(1,2);//(index,element)
//清空
list.clear();
//判断o是否在线性表中
System.out.println(list.contains(1));//true
System.out.println(list.containsAll(c));//true
//返回第一个o所在的下标
int index = list.indexOf(1);
//返回最后一个o的下标
int lastIndex = list.lastIndexOf(1);
//截取部分list
List<Integer> subList = list.subList(0,3);//[0,3)
subList.forEach(System.out::println);