Collection接口是层次结构中的根接口,构成Collection的单位称为元素。Collection接口通常不能直接使用,但该接口提供了添加元素、删除元素、管理数据的方法。由于List接口和Set接口都继承了Collection接口,因此这些方法对List集合和Set集合都是通用的。
实例代码:
package MyPackage_2;import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;public class TestClass {public static void main(String[] args) {Collection c1=new ArrayList();//实例化集合类对象String s1=new String("字符串对象");double s2=3.14;Object s3=new Object();c1.add(s1);//添加一个字符串对象c1.add(s2);//添加一格整数类型的数据c1.add(s3);//添加一个Object对象System.out.println("c1是否为空:"+c1.isEmpty()+" c1有"+c1.size()+"个元素");c1.remove(s3);System.out.println("\n调用remove函数之后:");System.out.println("c1是否为空:"+c1.isEmpty()+" c1有"+c1.size()+"个元素\n");Iterator it=c1.iterator();while(it.hasNext()){Object obj=it.next();System.out.println(obj);}}}
运行结果:
