- 集合
- 集合概念
- 和数组的区别:
- Collection 体系集合
- Collection 父接口
- Collection 使用
- 迭代器Iterator
集合概念
对象的容器,实现了对对象常用的操作方法。可实现数组的功能。(java.util.*)
和数组的区别: 1)数组长度固定,集合长度不固定;
2)数组可以存储基本类型和引用类型,集合只能存储引用类型。
特点:代表一组任意类型的对象,无序,无下标,不能重复
方法:
1)boolean add(Object obj) //添加一个对象;
2)boolean addAll(Collection c) //将一个集合中的所有对象添加到此集合中;
3)void clear() //清空此集合中的所有对象;
4)boolean contains(Object o) //检查此集合中是否包含o对象;
5)boolean equals(Object o) //比较此集合是否与指定对象相等;
6)boolean isEmpty() //判断此集合是否为空;
7)int size() //返回此集合中的元素个数;
8)boolean remove(Object o) //在此集合中移除o对象;
9)Object[] toArray() //将此集合转换成数组;
public class Demo1{
public static void main(String[] args){
Collection collection=new ArrayList();
// (1)添加元素
collection.add("apple");
collection.add("banana");
System.out.println("元素个数"+collection.size());
// (2)删除元素
collection.remove("apple");
System.out.println("元素个数"+collection.size());
// (3)遍历元素【重点】
// (3.1)使用增强for
for(Object object:collection){
System.out.println(object);
}
// (3.2) 使用迭代器(专门用来遍历集合的一种方式)
Iterator it=collection.iterator();
while(it.hasNext()){
String ob=(String)it.next();
System.out.println(ob);
it.remove();
}
// 判断元素
System.out.println(collection.contains("apple"));
System.out.println(collection.isEmpty());
}
}
迭代器Iterator
1)hasNext(); //有没有下一个元素
2)next(); //获取下一个元素
3)remove(); //删除当前元素。当使用迭代器的时候,并不能使用collection的其它方法来改变元素的。(并发修改)



