java hashset 相同_java HashSet判断元素重复的问题!

展开全部

因为你只重写了equals方法  没有重写hashCode方法

HashSet 判断元素是否相等 , 首先调用e68a843231313335323631343130323136353331333337623534hashCode方法,

如果hashCode的值一样,  那么调用equals方法,

如果equals方法也一样, 那么才算重复元素, 不在添加

所以没有重写hashCode方法的时候, stu2和stu3的hashCode值不一样,

你就可以添加两次相同的元素

修改后的代码import java.util.*;

class Student {

private String id;

private String name;

public Student(String id, String name) {

this.id = id;

this.name = name;

}

public String toString() {

return id + ":" + name;

}

public int HashCode() {

return this.id.hashCode();

}

public boolean equals(Object obj) {

if (this == obj) {

return true;

}

if (!(obj instanceof Student)) {

return false;

}

Student stu = (Student) obj;

boolean b = this.id.equals(stu.id);

return b;

}

public int hashCode() {//重写hashCode方法

final int prime = 31;

int result = 1;

result = prime * result + ((id == null) ? 0 : id.hashCode());

result = prime * result + ((name == null) ? 0 : name.hashCode());

return result;

}

}

public class xuexi {

public static void main(String[] args) {

HashSet hs = new HashSet();

Student stu1 = new Student("1", "Jack");

Student stu2 = new Student("2", "Rose");

Student stu3 = new Student("2", "Rose");

hs.add(stu1);

hs.add(stu2);

hs.add(stu3);

System.out.println(hs);

}

}

测试[2:Rose, 1:Jack]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值