一、什么是集合?
-
概念:
- 对象的容器,定义了多个对象进行操作的常用方法,可实现数组的功能;
-
和数组的区别:
- 数组的长度固定,集合长度不固定;
- 数组可以存储基本类型和引用类型,集合智能存储;
-
位置:
二、Collection接口
-
Collection是上图体系的跟接口,代表一组对象,称为“集合”
-
特点:
- 代表一组任意类型的对象,包含List和Set接口,所以是无序、无下标、不能重复;也可以描述为一部分是有序的,一部分是无序的。
-
方法:
- boolean add(Object obj) //添加对象
- boolean addALL(Collection c) //将一个集合中的所有对象添加到此结合中;
- void clear() //清空此集合中的所有对象
- boolean contains(Object o) //检查此集合中是否包含o对象
- boolean equals(Object o) //比较此集合是否与指定对象相等
- boolean isEmpty() //判断此集合是否为空
- boolean remove(Object o) //在此集合中移除o对象
- int size() //返回此集合中的元素个数
- Object[] toArray() //将此集合转换成数组
- iterator() //返回在此集合上的元素上进行迭代的迭代器(完成遍历)
-
List接口的特点:
-
Set接口的特点:
-
Collection集合的使用
Collection collection = new ArrayList();
collection.add("香蕉");
collection.add("西瓜");
collection.add("榴莲");
System.out.println("集合中元素个数为:"+collection.size());
System.out.println(collection);
collection.remove("榴莲");
for (Object obj:collection
) {
System.out.println(obj);
}
System.out.println("----------");
Iterator it =collection.iterator();
while(it.hasNext()){
String s =(String)it.next();
System.out.println(s);
it.remove();
}
collection.isEmpty();