package cn.itheima.HashSet;
import java.util.HashSet;
import java.util.Iterator;
/**
* 一个HashSet题
* @author czm
*
*/
class User{
String name;
String pssword;
public User(String name, String iD) {
this.name = name;
pssword= iD;
}
@Override
public int hashCode() {
return this.name.hashCode()+this.pssword.hashCode();
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
User book = (User)obj;
return this.name.equals(book.name)&&this.pssword.equals(book.name);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "{用户名是:"+this.name+" 密码是:"+this.pssword+"}";
}
}
public class MyHashSet {
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.name.equals("李四")) {
user.name = "赵六";
set.remove(user); //@@@@
}
}
System.out.println(set);
}
}
输出的结果是:[{用户名是:张三 密码是:123}, {用户名是:赵六 密码是:234}]
那么问题就来了,@@@@的地方已经删除了,为什么会删除不了呢?
import java.util.HashSet;
import java.util.Iterator;
/**
* 一个HashSet题
* @author czm
*
*/
class User{
String name;
String pssword;
public User(String name, String iD) {
this.name = name;
pssword= iD;
}
@Override
public int hashCode() {
return this.name.hashCode()+this.pssword.hashCode();
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
User book = (User)obj;
return this.name.equals(book.name)&&this.pssword.equals(book.name);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "{用户名是:"+this.name+" 密码是:"+this.pssword+"}";
}
}
public class MyHashSet {
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.name.equals("李四")) {
user.name = "赵六";
set.remove(user); //@@@@
}
}
System.out.println(set);
}
}
输出的结果是:[{用户名是:张三 密码是:123}, {用户名是:赵六 密码是:234}]
那么问题就来了,@@@@的地方已经删除了,为什么会删除不了呢?