专注Java教育14年 全国咨询/投诉热线:400-8080-105
动力节点LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 java hashset实现原理及工作原理

java hashset实现原理及工作原理

更新时间:2020-08-17 16:50:29 来源:动力节点 浏览2879次

 

概述

This class implements the Set interface, backed by a hash table (actually a HashMap instance). 
It makes no guarantees as to the iteration order of the set; in particular, 
it does not guarantee that the order will remain constant over time. 
This class permits the null element.This class implements the Set interface, backed by a hash table (actually a HashMap instance). 
It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. 
This class permits the null element.

HashSet是基于HashMap来实现的,操作很简单,更像是对HashMap做了一次“封装”,而且只使用了HashMap的key来实现各种特性,我们先来感性的认识一下这个结构:

HashSet set = new HashSet();
set.add("语文");
set.add("数学");
set.add("英语");
set.add("历史");
set.add("政治");
set.add("地理");
set.add("生物");
set.add("化学");

其大致的结构是这样的:

 

java hashset实现原理

private transient HashMap map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

map是整个HashSet的核心,而PRESENT则是用来造一个假的value来用的。Map有键和值,HashSet相当于只有键,值都是相同的固定值,即PRESENT。

 2. 基本操作

public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}
public boolean remove(Object o) {
    return map.remove(o)==PRESENT;
}
public boolean contains(Object o) {
    return map.containsKey(o);
}
public int size() {
    return map.size();
}

基本操作也非常简单,就是调用HashMap的相关方法,其中value就是之前那个dummy的Object。

 

java hashset实现原理

以上就是动力节点java培训机构的小编针对“Java hashset实现原理及工作原理”的内容进行的回答,希望对大家有所帮助,如有疑问,请在线咨询,有专业老师随时为你服务。

 

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>