Collection中的removeAll方法

   public boolean removeAll(Collection<?> c)  

  移除此 collection 中那些也包含在指定 collection 中的所有元素(可选操作)。此调用返回后,collection 中将不包含任何与指定 collection 相同的元素。

 

import java.util.*;
import java.io.Serializable;
public class TestRemoveAll{
	public static void main(String[] args){
		//测试removeAll方法
		/*
		//removeAll在数据量很大的情况下是不适合用的
		List<Double> testList = new ArrayList<Double>();

		for(Double i=0.0;i<655355;i++){
			testList.add(i);
	    }
	    List<Double> test = new ArrayList<Double>();
	    for(Double i=0.0;i<6555;i++){
		  test.add(i);
	    }
		Long l = System.currentTimeMillis();
		testList.removeAll(test);
		System.out.println(System.currentTimeMillis()-l);
		*/
		List<Student> lists = new ArrayList<Student>();
		lists.add(new Student("1","Lucy",20));
		lists.add(new Student("2","Mary",23));
		lists.add(new Student("3","Neck",22));
		List list1 = new ArrayList();
		list1.add(new Student("2","Mary",23));
		list1.add(new Student("3","Neck",22));
		lists.removeAll(list1);
		for(Student list: lists){
			System.out.println(list.getId()+"                 "+list.getName()+"            "+list.getAge());
	    }
	}
}

class Student implements Serializable{
    private String id;
    private String name;
    private Integer age;
    public Student(){}
    public Student(String id,String name ,Integer age){
		this.id = id;
		this.name = name;
		this.age = age;
    }

    public void setId(String id){
		this.id = id;
	}
	public void setName(String name){
		this.name = name;
    }
    public void setAge(Integer age){
		this.age = age;
	}
	public String getId(){
		return id;
	}
	public String getName(){
		return name;
	}
	public Integer getAge(){
		return age;
	}
         //覆盖equals方法 注意参数为:Object类型
	public boolean equals(Object obj){
        Student stu = (Student)obj;
        boolean flag = true;
        if(!stu.getId().equals(id)){
			flag = false;
		}else if(!stu.getName().equals(name)){
		    flag = false;
		}else if(stu.getAge()!=age){
			flag = false;
		}
		return flag;
    }
    /*public int hashCode(){
        return 0;
	}*/
}

 

 

  问题1:覆盖了equals方法是否一定覆盖hashCode方法

  http://www.exam8.com/computer/djks/dj2/Java/ziliao/200810/1314425.html

  问题2:removeAll方法在数据量很大的情况下,是不适合用的,该用什么方法来解决呢

 

  另外还有retainAll

  public boolean retainAll(Collection<?> c)

 仅保留此 collection 中那些也包含在指定 collection 的元素(可选操作)。换句话说,移除此 collection 中未包含在指定 collection 中的所有元素。

此实现在此 collection 上进行迭代,依次检查该迭代器返回的每个元素,以查看其是否包含在指定的 collection 中。如果不是,则使用迭代器的 remove 方法将其从此 collection 中移除。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值