Collection集合常用功能以及Iterator接口介绍
Collection集合
单列集合的体系结构:

Collection集合常用的方法
boolean add(E e); 向集合中添加元素
boolean remove(E e); 删除集合中的某个元素
void clear(); 清空集合所有的元素
boolean contains(E e) 判断集合中是否包含某个元素
boolean isEmpty(); 判断集合是否为空
int size(); 获取集合的长度
Object[] toArray(); 将集合转成一个数组
public static void main(String[] args) { Collection<String> coll = new ArrayList<>(); // boolean add(E e); 向集合中添加元素 coll.add("Hello"); coll.add("World"); coll.add("张三"); coll.add("李四"); System.out.println(coll); // boolean remove(E e); 删除集合中的某个元素 // boolean remove = coll.remove("张三"); // System.out.println(remove); // System.out.println(coll); // void clear(); 清空集合所有的元素 // coll.clear(); // System.out.println(coll); // boolean contains(E e) 判断集合中是否包含某个元素 boolean world = coll.contains("World"); System.out.println(world); // boolean isEmpty(); 判断集合是否为空 boolean empty = coll.isEmpty(); System.out.println(empty); // int size(); 获取集合的长度 int size = coll.size(); System.out.println(size); // Object[] toArray(); 将集合转成一个数组 Object[] objects = coll.toArray(); for (int i = 0; i < objects.length; i++) { System.out.println(objects[i]); } }
Iterator接口介绍
迭代:即Collection集合元素的通用获取方式,在取元素之前先要判断集合中有没有元素,
如果有,就把这个元素取出来继续判断,如果还有就再取出来。已知把集合中的所有元素全部取出。
Iterator接口的常用方法:
public E next():返回迭代的下一个元素。
public boolean hashNext():如果仍有元素可以迭代,则返回true。
迭代器的使用步骤:
1.使用集合中的方法iterator()获取迭代器的实现类对象,使用Iterator接口接收(多态)
2.使用Iterator接口中的方法hasNext判断还有没有下一个元素
3.使用Iterator接口中的方法next取出集合中的下一个元素

浙公网安备 33010602011771号