public class vc {
//接口多态的方式调用
public static void showColl() {
Collection<String> coll = new ArrayList<String>();
coll.add("ad");
coll.add("ads");
coll.add("adc");
System.out.println(coll);
coll.clear();
System.out.println(coll);
}
public static void main(String[] args) {
//迭代器的使用
Collection<String> coll = new ArrayList<String>();
coll.add("s");
coll.add("c");
coll.add("r");
Iterator<String> iter = coll.iterator();
// boolean has = iter.hasNext();
// String s = iter.next();
while(iter.hasNext()) {
String s = iter.next();
System.out.println(s);
}
//也可以使用for循环实现迭代
for (Iterator<String> iter1 = coll.iterator(); iter1.hasNext(); ) {
System.out.println(iter1.next());
}
//集合可以存任何类型的元素最好在使用集合最好加上类型,这样就不需要强转了
Collection a = new ArrayList();
a.add(5);//迭代器如何获取
a.add("a");
for(Iterator it = a.iterator();it.hasNext();) {
System.out.println(it.next());
}
showColl3();
}
private static void showColl3() {
// TODO Auto-generated method stub
Collection<String> coll = new ArrayList<String>();
coll.add("a");
coll.add("b");
coll.add("v");
coll.add("c");
coll.remove("c");
System.out.println(coll);
}
private static void showColl2() {
// TODO Auto-generated method stub
Collection<String> coll = new ArrayList<String>();
coll.add("a");
coll.add("b");
coll.add("v");
coll.add("c");
Object [] obj = coll.toArray();
for (int i = 0; i < obj.length; i++) {
System.out.println(obj[i]);
}
}
private static void showColl1() {
// TODO Auto-generated method stub
Collection<String> coll = new ArrayList<String>();
coll.add("dsd");
coll.add("ss");
System.out.println(coll.size());
}
}
public static void main(String[] args) {
//ArrayList元素有序可以重复
Collection c = new ArrayList();//创建一个集合,该集合可以存放任何类型的元素,这样会有弊端,不安全,想操作集合元素时必须做相应向下的转型
c.add("孙悟空");//虽然集合不支持基本类型,但有自动装箱,这是添加功能
c.add(6);
System.out.println("该集合元素的个数为:"+c.size());//获取集合的长度
c.remove(6);//这是删除功能,删除指定的元素
System.out.println("该集合元素的个数为:"+c.size());
System.out.println(c.contains("孙悟空"));//这是判断该集合中是否包含指定的元素
//集合接口的另一个实现类HashSet元素无序不可重复
Collection co = new HashSet();//指定为String类型的元素
co.add("疯狂讲义");
System.out.println("c集合是否完全包含co集合?"+c.containsAll(co));
c.removeAll(co);
System.out.println(co.size());
//迭代器遍历集合
for(Iterator it = c.iterator();it.hasNext();) {
System.out.println(it.next());
}