JAVA小练习137——hashSet的疑惑

import java.util.HashSet;
import java.util.Iterator;

class User{
	
	String userName;
	
	String password;

	public User(String userName, String password) {
		super();
		this.userName = userName;
		this.password = password;
	}
	
	
	@Override
	public int hashCode() {
		return this.userName.hashCode()+ this.password.hashCode();
	}
	
	
	@Override
	public boolean equals(Object obj) {
		User user = (User)obj;
		return this.userName.equals(user.userName)&&this.password.equals(user.password);
	}
	
	@Override
	public String toString() {
		return "{用户名:"+ this.userName +" 密码:"+ this.password+"}";
	}	
}



public class Demo137 {

	public static void main(String[] args) {
		HashSet<User> set = new HashSet<User>();
		set.add(new User("狗娃","123"));
		set.add(new User("狗剩","234"));
		//删除
		Iterator<User> it = set.iterator();
		 while(it.hasNext()){
			 User user = it.next();
			 if(user.userName.equals("狗剩")){
				 //修改用户名
				 user.userName = "铁蛋";
				 //为什么改名后就无法删除这个元素了呢?因为重写了hashcode方法后,一改名,经过计算的存储位置就不是原位置了,指向了一个新位置,而这个位置并没有存储东西,删的是这个新位置上的数据
				 set.remove(user);
			 }
		 }
		System.out.println("集合的元素:"+ set);
		
		
	}
	
}



猜你喜欢

转载自blog.csdn.net/Eric_The_Red/article/details/91972445