java基础:Set之HashSet

Set集合首先来说它的特点有:元素是无序的(存入和取出的顺序不一定一致),元素不可重复。

这一篇主要是讲解Set集合里面的HashSet。

HashSet:底层的数据结构是哈希表。


        那么问题来了,如果HashSet元素不可重复,那么HashSet是如何保证元素的唯一性的呢?
        其实HashSet是通过元素的两个方法,Hashcodeeqauls来完成。
        如果元素Hashcode相同,才会判断eqauls是否为true
        如果元素Hashcode不相同,会进一步调用eqauls判断元素是否相同
        注意,对于判断元素是否存在,以及删除等操作,依赖的方法是元素Hashcodeeqauls方法。

我们对HashSet主要也是需要了解它是怎么保证元素唯一性的。

我们可以通过如下代码简要的描述HashSet保证元素唯一性的过程:

package com.L.HashSet;

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

public class HashSetL {

	public static void main(String[] args) {
		HashSet hs = new HashSet();
		hs.add(new Student("L01", 18));
		hs.add(new Student("L02", 19));
		hs.add(new Student("L02", 19));
		hs.add(new Student("L03", 21));
		hs.add(new Student("L03", 20));
		hs.add(new Student("L04", 21));
		Iterator it = hs.iterator();
		while (it.hasNext()) {
			Student stu = (Student) it.next();
			System.out
					.println("name:" + stu.getName() + ",age:" + stu.getAge());
		}
	}

}

class Student {
	private String name;
	private int age;

	Student(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public int hashCode() {
		return name.hashCode() + age * 13;//使每个元素的哈希值都各不相同
	}

	public boolean equals(Object obj) {
		if (!(obj instanceof Student)) {//若对象不是Student则对象不存入
			return false;
		}
		Student stu = (Student) obj;
		if (this.name.equals(stu.name)) {//判断是否有重复元素
			System.out.println(stu.name + "有重复元素");
		}
		return this.name.equals(stu.name) && this.age == stu.age;//返回判断结果
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}
}

总言之HashSet底层的数据结构是哈希表,由哈希表的性质我们可以知道,我们确保存入的元素具有不同的哈希值,我们就可以确保元素的唯一性。但是如果哈希值相同,我们就需要进一步的对元素经行比较,就是覆写equals方法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值