HashSet 如何保证元素不重复?

abcjavabc 2013-12-24 08:40:52
HashSet是如何保证元素不重复的
...全文
573 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Zhuzhuxia_1993 2015-12-08
  • 打赏
  • 举报
回复
引用 楼主 goutoudashen 的回复:
HashSet是如何保证元素不重复的
那么是系统自带的还是认为的输入呢?
teemai 2013-12-24
  • 打赏
  • 举报
回复
归根结底你还是要去理解下Hash算法。
末日哥 2013-12-24
  • 打赏
  • 举报
回复
看hashmap源码
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
先判断的hashCode,hashCode不同,则元素值一定不同。 hashCode相同,但元素未必相同,还需调用equals判断 如果equals为true,则相同,排除此元素
solomon5926 2013-12-24
  • 打赏
  • 举报
回复
分析源代码

 private transient HashMap<E,Object> map;
/**
     * Adds the specified element to this set if it is not already present.
     * More formally, adds the specified element <tt>e</tt> to this set if
     * this set contains no element <tt>e2</tt> such that
     * <tt>(e==null ? e2==null : e.equals(e2))</tt>.
     * If this set already contains the element, the call leaves the set
     * unchanged and returns <tt>false</tt>.
     *
     * @param e element to be added to this set
     * @return <tt>true</tt> if this set did not already contain the specified
     * element
     */
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
HashSet的底层是通过HashMap来实现,因为HashMap有key做保证,所有HashMap不会重复,所有HashSet也不会重复,key就相当于我们数据库中保证唯一性的ID字段。
林亻乔 2013-12-24
  • 打赏
  • 举报
回复
HashSet在存放某个元素时,会先获取该元素的hashcode值,然后进行一系列的运算,之后确定将元素存放在什么位置。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧