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 中移除。