Set集合判断对象重复的⽅法
Set<User> userSet = new HashSet<>();
User user1= new User("aa","11");
User user2= new User("aa","11");
userSet.add(user1);
userSet.add(user2);
System.out.println("set size"+userSet.size());
Iterator iterator = userSet.iterator();
while (iterator.hasNext()){
System.out.().toString());
}
创建两个相同的对象没有重写对象的equals⽅法和hashcode⽅法默认使⽤object的。并且依次添加到set中,成功添加了两个
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(username, user.username) &&
Objects.equals(pwd, user.pwd);
}
@Override
public int hashCode() {
return Objects.hash(username, pwd);
}
重写⽅法之后只添加成功了⼀个对象 set的⼤⼩为1
如果只是重写equals⽅法不重写hashcode⽅法 set中任然有两个对象并且hashcode不同,set集合区分两个对象是否相同是使⽤hashcode 值进⾏区分的。
Object类的equals⽅法:⽐较两个对象是否是同⼀个引⽤ java.lang.Object
public boolean equals(Object obj) {
return (this == obj);
}
关于equals⽅法和hashcode⽅法。equals()方法
注:String类型的equals⽅法只⽐较内容不⽐较是否来引⽤同⼀个对象
public static void main(String[] args) {
Set<User> userSet = new HashSet<>();
User user1= new User("aa","11");
User user2= new User("aa","11");
userSet.add(user1);
userSet.add(user2);
System.out.println("set size"+userSet.size());
Iterator iterator = userSet.iterator();
while (iterator.hasNext()){
System.out.().toString());
}
System.out.println("equals?:"+user1.equals(user2));
System.out.println("user1:hashcode:"+user1.hashCode());
System.out.println("user2:hashcode:"+user2.hashCode());
}
}
class User{
String username;
String pwd;
public User(String username, String pwd) {
this.username = username;
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; User user = (User) o;
return Objects.equals(username, user.username) && Objects.equals(user.pwd,pwd);
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论