Set 接口

Set类集合的特点:

	1.无序
	2.唯一
	3.只能存储一个null值
Set<String> set=new HashSet();
		set.add(null);
		set.add(null);
		set.add("cv");
		set.add("we");
		set.add("cv");
打印结果:[null, cv, we]

HashSet

特点:

无序
唯一
只能有一个null值

问题:

  • 1.HashSet是如何保证元素唯一的?
    hashCode equals
  • 2.HashSet是如何导致元素无序?
    元素存储到哈希表结构当中是通过 对象的hashCode经过某种运算产生的相对不确定的数
  • 3.HashSet为什么和存储不一样,却每次遍历的顺序都一样?
    因为每次遍历的时候是同一个对象,同一个对象产生的哈希值是一样的

使用set添加对象时,为什么要重写hashcode方法?
因为对象在生成的时候,会随机生成不同的hashcode值,
但hashcode方法是根据对象的内容生成的值,重写hashcode方法以后,相同内容则hash值相同
其实最主要是为了满足Set集合的add机制,因为add转集合的put,该方法要比较hash 和equals

public class Set_02 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Set<Student> sr=new HashSet();
		sr.add(new Student("ljx",89.5));
		sr.add(new Student("ljx",89.5));
		sr.add(new Student("ljx1",87.5));
		sr.add(new Student("ljx",89.5));
		System.out.println(sr);
	}

}
class Student{
	String name;
	Double Score;
	@Override
	public String toString() {
		return "Student [name=" + name + ", Score=" + Score + "]";
	}
	public Student(String name, Double score) {
		super();
		this.name = name;
		Score = score;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((Score == null) ? 0 : Score.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (Score == null) {
			if (other.Score != null)
				return false;
		} else if (!Score.equals(other.Score))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值