1、Collection 中能存放什么元素?
没有使用“泛型”之前,Collection 中可以存储 Object 的所有子类型。
使用了“泛型”之后,Collection 中只能存放某个具体的类型。
注:集合中不能直接存储基本数据类型,也不能存Java对象,只是存储Java对象的内存地址
2、Collection 中的常用方法
通过以下代码进行理解:
import java.util.ArrayList;
import java.util.Collection;
public class Test5 {
public static void main(String[] args) {
//接口是抽象的,无法实例化
//多态
Collection c = new ArrayList();
c.add(100);//自动装箱,实际上放进了一个对象的内存地址。
c.add(new Object());
c.add(true);//自动装箱
//获取集合中元素的个数
System.out.println("集合中元素个数为:" + c.size());
//清空集合
c.clear();
System.out.println("集合中元素个数为:" + c.size());
//再向集合中添加元素
c.add("hello");
c.add("world");
c.add("小花");
c.add(10);
//判断集合中是否有某个元素
boolean flag = c.contains("小花");
System.out.println(flag);
//删除集合中某个元素
c.remove(10);
System.out.println("集合中元素个数为:" + c.size());
//判断集合是否为空
System.out.println(c.isEmpty());
c.clear();
System.out.println(c.isEmpty());
System.out.println("===================");
c.add("hello");
c.add("world");
c.add("小花");
c.add(10);
//转化为数组
Object[] objs = c.toArray();
for(int i = 0 ;i < objs.length;i++){
System.out.println(objs[i]);
}
}
}
输出结果为: