集合
-
概念:对象的容器,定义了对多个对象进行操作的常用方法。可实现数组的功能。
-
和数组的区别:
-
数组长度固定,集合长度不固定
-
数组可以存储基本类型和引用类型,集合只能存储引用类型
-
Collection父接口
-
特点:代表一组任意类型的对象,无序、无下标、不能重复。
-
方法:
-
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() //将此集合转换成数组
-
Collection的使用:保存字符串
代码示例:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo01 {
public static void main(String[] args) {
//创建集合
Collection collection = new ArrayList();
//(1)添加元素
collection.add("苹果");
collection.add("西瓜");
collection.add("榴莲");
System.out.println("元素个数:"+collection.size());
System.out.println(collection);
//(2)删除元素
collection.remove("榴莲");
System.out.println("删除之后:"+collection.size());
System.