package Collection;
import java.util.ArrayList;
import java.util.Iterator;
//import javax.xml.crypto.AlgorithmMethod;
/*
1. add方法的参数 类型是Object,以便于接收任意类型的对象
2. 集合中存储的都是对象的引用(地址)
迭代器:就是集合取出元素的方式
*/
public class ClloectionDemo
{
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
// method2();
method_get();
}
public static void method_get()
{
ArrayList<String> al = new ArrayList<String>();
al.add("java1");
al.add("java2");
al.add("java3");
// sop(al);
// iterator():返回Iterator接口的子对象
// 接口型引用只能指向自己接口的子类对象,该对象是从集合对象中的方法 new 出来的
//Iterator it = al.iterator();
/* One
while (it.hasNext())
{
sop(it.next());
}
*/
/* Two
for (int i = 0; i < al.size(); i++)
{
sop(it.next());
}
*/
// Three
for(Iterator itt = al.iterator();itt.hasNext(); )
{
sop(itt.next());
}
}
public static void method2()
{
ArrayList<String> al = new ArrayList<String>();
al.add("java1");
al.add("java2");
al.add("java3");
ArrayList<String> a2 = new ArrayList<String>();
a2.add("java1");
a2.add("java5");
a2.add("java6");
// 取交集,取相同的元素
//al.retainAll(a2);
al.removeAll(a2);
sop("al: "+al);
sop("a2: "+a2);
}
public static void base_method()
{
//创建一个集合容器,使用Collection 接口的子类。ArrayList
ArrayList<String> al = new ArrayList<String>();
// 添加
al.add("heh");
al.add("dhf");
al.add("fdjkgd");
// 打印
sop("原集合:"+al);
//删除
al.remove("heh");
sop(al);
// 清空集合
al.clear();
// 是否为空
sop("是否为空:"+al.isEmpty());
// 判断元素
sop("heh是否存在:"+al.contains("heh"));
// 获取集合长度
sop("size: "+al.size());
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
原文:http://www.cnblogs.com/IamJiangXiaoKun/p/4639305.html