ort java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;public class TestCollection {
public static void main(String[] args) {
Collection collect = new HashSet();
//测试add方法
collect.add("first");
collect.add("second");
collect.add("third");
//测试contains方法
if(collect.contains("first")){
System.out.println("系统包含first");
}
//测试size方法
if(collect.size()!=0){
System.out.println("集合中共有"+collect.size()+"个元素");
}
//测试remove方法
collect.remove("first");
if(!collect.contains("first")){
System.out.println("已经删除first");
}
//测试containsAll方法
Collection subcollect = new HashSet();
subcollect.add("second");
subcollect.add("third");
if(collect.containsAll(subcollect)){
System.out.println("subcollect是collect的子集");
}
//测试allAll方法
Collection subcollect_2 = new HashSet();
subcollect_2.add("four");
subcollect_2.add("five");
System.out.println("添加一个集合"+collect.addAll(subcollect_2));//添加一个集合
System.out.println("添加本身已经有的一个子集"+collect.addAll(subcollect));//添加本身已经有的一个子集
//测试retainAll方法
subcollect_2.retainAll(subcollect_2);
Iterator it = collect.iterator();
while(it.hasNext()){
System.out.println("集合中包含有元素:"+it.next());
}

System.exit(0);
}
}为什么集合中还会有second和third这两个元素?

解决方案 »

  1.   

    不是很正常吗?你在哪里remove掉second和third?
    你就collect.remove("first");了
      

  2.   


           //测试retainAll方法
            subcollect_2.retainAll(subcollect_2);//我怀疑你这里,你是不是想写成如下的?是不是你写错了?
            subcollect_2.retainAll(collect);
      

  3.   

     subcollect_2.retainAll(subcollect_2);这句话我写错了!~:)
      

  4.   

    我是想写
     collect.retainAll(subcollect_2);
      

  5.   

    sorry, 改为collect.retainAll(subcollect_2);