- 为什么讲collection接口?
- 因为collection是所有List和Set接口的爸爸,collection有的方法,继承他的接口和实现它的类都有这个方法。
-
Collection中能存放什么元素?
- 没有使用泛型之前,Collection可以存储Object的所有子类型
- 使用泛型后,Collection只能存储某个具体类型
-
java.util.Collection 方法的常用方法
- boolean add(Object o) 向集合中添加元素
- int size() 获取集合中元素的个数
- void clear() 清空集合
- boolean contains(Object o) 判断集合中是否有o
- boolean remove( Object o) 删除某个元素
- boolean isEmpty() 判断集合是否为空
- Object[] toArray 转换成数组的方法
package collection;
import oop.demo01.Student;
import java.util.ArrayList;
import java.util.Collection;
/*
java.util.Collection 方法的常用方法
*/
public class CollectionTest01 {
public static void main(String[] args) {
//创建一个集合对象
//Collection c = new Collection(); //接口是抽象的,无法实例化
//多态
Collection c = new ArrayList<>();
//测试Connection接口中的常用方法
//=向集合添加元素
c.add(1200);//自动装箱,实际是放进了一个对象的内存地址 Integer x = new Integer(1200)
c.add(3.14);//自动装箱
c.add(new Object());
c.add(new Student());
c.add(true);//自动装箱
//获取集合中元素的个数
System.out.println(c.size());//5
//清空集合
c.clear();
System.out.println(c.size());//0
c.add("hello");
c.add("world");
//判断集合中是否有hello
boolean flag = c.contains("hello");
System.out.println(flag); //true
//删除集合中的某个元素
c.remove("world");
System.out.println(c.size()); //1
//判断集合是否为空
System.out.println(c.isEmpty());//false
//转换成数组
c.add(123);
c.add(456);
c.add(789);
c.add(new Student());
Object[] objs = c.toArray();
for (int i = 0; i < objs.length; i++) {
Object o = objs[i];
System.out.println(o);
}
}
public static void student(){
}
}