标签:
HashSet内部是用的HashMap,只用了HashMap的key。
public class User implements Cloneable{ private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } public boolean equals(Object obj) { if(this == obj) { return true; } if(!(obj instanceof User)) { return false; } User user = (User)obj; //if(this.name==user.name && this.age==user.age) if(this.name.equals(user.name) && this.age==user.age) { return true; } else { return false; } } public int hashCode() { return name.hashCode() + age; } public String toString() { return "{name:‘" + name + "‘,age:" + age + "}"; } public Object clone() { Object object = null; try { object = super.clone(); } catch (CloneNotSupportedException e) {} return object; } public void setAge(int age) { this.age = age; } public String getName() { return name; } }
1 import java.util.Collection; 2 import java.util.Iterator; 3 import java.util.concurrent.CopyOnWriteArrayList; 4 5 /** 6 * 迭代集合的时候不能增加、删除,如果修改了,next()方法中的版本号就会出现不一致了。 7 * @author LiTaiQing 8 * 9 */ 10 public class CollectionModifyExceptionTest { 11 public static void main(String[] args) { 12 Collection<User> users = new CopyOnWriteArrayList<User>(); 13 14 //new ArrayList(); 15 users.add(new User("张三",28)); 16 users.add(new User("李四",25)); 17 users.add(new User("王五",31)); 18 Iterator<User> itrUsers = users.iterator(); 19 while(itrUsers.hasNext()){ 20 System.out.println("aaaa"); 21 User user = (User)itrUsers.next(); 22 if("李四".equals(user.getName())){ 23 users.remove(user); 24 //itrUsers.remove(); 25 } else { 26 System.out.println(user); 27 } 28 } 29 } 30 }
标签:
原文地址:http://www.cnblogs.com/litaiqing/p/4651319.html