集合对我们来说一直是一个难点
集合是一个容器可以变长的存放各种类型的对象。
above all,Collection是最上层的接口所以他的方法,实现他的类都可以使用。
Collection的常见方法:
1、添加:
boolean add(Object obj);
boolean addAll(Collection coll);
2、删除:
boolean remove(Object obj);
boolean removeAll(Collection coll);
void clear();
3、判断:
boolean contains(Object obj);
boolean containsAll(Collection coll);
boolean isEmpty();判断集合中是否有元素。
4、获取:
int size();
Iterator iterator();
取出元素的方式:迭代器。
该对象必须依赖于具体容器,因为每一个容器的数据结构都不同,所以该迭代器对象是在容器中进行内部实现的,也就是iterator方法在每个容器中的实现方式是不同的。
对于使用容器者而言,具体的实现不重要,只要通过容器获取到该实现的迭代器的对象即可,也就是iterator方法。
Iterator接口就是对所有的Collection容器进行元素取出的公共接口。
5、其他:
boolean retainAll(Collection coll);取交集
Object toArray();将集合转成数组
import java.util.ArrayList; import java.util.Collection; import org.junit.Test; public class CollectionDemo { @Test public void test1(){ Collection coll=new ArrayList(); //添加元素 coll.add("a"); coll.add("b"); coll.add("c"); coll.add("d"); System.out.println(coll); //删除元素 coll.remove("a"); coll.remove("b"); System.out.println(coll); //清空集合 coll.clear(); System.out.println(coll); } @Test public void test2(){ Collection c1=new ArrayList(); Collection c2=new ArrayList(); //给c1添加元素 c1.add( "abc1"); c1.add( "abc2"); c1.add( "abc3"); c1.add( "abc4"); //给c2添加元素 c2.add( "abc2"); c2.add( "abc6"); c2.add( "abc7"); System.out.println( "c1:" + c1); System.out.println( "c2:" + c2); //演示addAll //将c2中的元素添加到c1中 c1.addAll(c2); //演示removeAll //从c1集合中删除与c2集合相同的元素 boolean b = c1.removeAll(c2); System.out.println( "removeAll:" + b); //演示containsAll boolean b1 = c1.containsAll(c2); System.out.println( "containsAll:" + b1); //演示retainAll //取交集,保留和指定的集合相同的元素 boolean b2 = c1.retainAll(c2); System.out.println( "c1、c2交集:" + c1); } }
使用迭代器
import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class IteratorDemo { public static void main(String[] args) { // TODO Auto-generated method stub Collection coll=new ArrayList(); coll.add("a"); coll.add("b"); coll.add("c"); coll.add("d"); System.out.println(coll); Iterator it=coll.iterator(); while(it.hasNext()){ System.out.println(it.next()); for (Iterator iterator = coll.iterator(); iterator.hasNext();) { System.out.println(iterator.next()); } } } }