包装类 与 简单集合框架(二)

2014-11-24 10:33:35 · 作者: · 浏览: 1
boolean add(Collection col);添加集合元素
删除
boolean remove(Object obj);
boolean removeAll(Collection col);//删除该集合中和col共有的元素,即删除交集。
boolean retainAll(Collection col);//删除该集合中不在col中的所有元素。
判断
boolean contains(Object obj);
boolean contains (Collection col);
boolean isEmpty();
获取
int size();//返回集合中的元素个数
Object [] toArray();//返回包含此 collection 中所有元素的数组。
[java]
package Collection;

import java.util.ArrayList;
import java.util.Collection;

public class CollectionDemo {
public static void main(String[] args) {
//创建集合类对象
Collection col1 = new ArrayList();
Collection col2 = new ArrayList();
// show(col1);
show(col1, col2);

}

public static void show(Collection col1, Collection col2) {
col1.add("love01");
col1.add("love02");
col1.add("love03");
col1.add("love04");
col2.add("love02");
col2.add("love03");
// col2.add("love07");
// col2.add("love08");
System.out.println("col1 = " + col1);
System.out.println("col2 = " + col2);
// boolean b = col1.addAll(col2);
// System.out.println("addAll "+b);
// boolean b = col1.removeAll(col2);
// System.out.println("removeAll "+b);
System.out.print(col1.containsAll(col2));
System.out.print(col1.contains("love04"));
// System.out.println("col1 = " + col1);

}

public static void show(Collection col) {
col.add("i");
col.add("love");
col.add("u");
System.out.println(col);
col.remove("u");
System.out.println(col);
}

}


Iterator的简单介绍
Iterator 迭代器类型的对象 需要用到集合类的 iterator()方法获得。同步不安全
如: //创建集合对象
Collection col = new ArrayList();
//通过集合类获得迭代器对象
Iterator it = col.iterator(); // 和在获取同步锁的监视器有类似。
//创建一个锁
ReentrantLock lock = new ReentrantLock();
//分别获取该锁上的两组监视器对象,一组用来监视生产者,一组用来监视消费者。
Condition producer_con = lock.newCondition();
Condition consumer_con = lock.newCondition();
迭代器对象的只有三个方法即为:
boolean hasNext();//是否仍有元素可以迭代。
E next();//返回下一个迭代的元素。
void remove()//从迭代器指向的 collection 中移除迭代器返回的最后一个元素(可选操作).
[java]
package Collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class IteratorDemo {

/**
* Iterator迭代器的方法演示
*
*/
public static void main(String[] args) {
//创建集合对象
Collection col = new ArrayList();

show(col);
}

public static void show(Collection col) {
//添加元素
col.add("love01");
col.add("love02");
col.add("love03");
col.add("love04");
System.out.println(