java 板


LINE

tkcn , good guess!!! thank you for your response after tracing JDK(1.4.2) HashSet I have some answer here. First of all, Inside HashSet there is a HashMap to store objects. ※ 引述《tkcn (小安)》之铭言: : ※ 引述《lin1000 (你是研究生吗)》之铭言: : : hash.add(o); : : hash.add(o); : : hash.add(o1); : HashSet 可以放同一个物件两次吗? :P : 我没有去看 HashSet 的 source code : 但是我猜想流程大概是以下这个样子 : 1. 呼叫传入物件的 hashcode(),计算出物件存放的位址 that's right! HashMap use a static method to calculate int hash int hash = hash(k); static int hash(Object x) { int h = x.hashCode(); h += ~(h << 9); h ^= (h >>> 14); h += (h << 4); h ^= (h >>> 10); return h; } : 2a. 如果该位址尚未存放其他物件,则将传入的物件存入。接着结束这个 method。 that's right! and will return null to the the caller. : 2b. 若该位址已经有物件,并且是同一个物件 (使用 == ),则结束这个 method。 inside HashMap there is a static inner class Entry to wrap data transient Entry[] table; <----- instance variable static class Entry implements Map.Entry { final Object key; Object value; final int hash; Entry next; <------ Entry itself has a referece to another one } so we can say that JDK use linked list way to handle address collision if there is a "same" key object , replace the value object by a new value object. finally return the value object which has been replaced (the old one) As to the definition of "same" key object, we can see the following code from jdk(1.4.2) HashMap source : if (e.hash == hash && eq(k, e.key)) { <------ this line Object oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } static boolean eq(Object x, Object y) { return x == y || x.equals(y); } : 3. 呼叫 equals(),若回传 true 不做任何处理, : 回传 false,则存放这个物件 : ( 我不知道 HashSet 如何处理 hashcode 相同的存放问题, : 可能是存再下一个位址, : 或着是在同一个位址使用一个 collection 存放两个以上的物件 ) --



※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 202.178.206.10 ※ 编辑: lin1000 来自: 202.178.206.10 (04/28 00:12)







like.gif 您可能会有兴趣的文章
icon.png[问题/行为] 猫晚上进房间会不会有憋尿问题
icon.pngRe: [闲聊] 选了错误的女孩成为魔法少女 XDDDDDDDDDD
icon.png[正妹] 瑞典 一张
icon.png[心得] EMS高领长版毛衣.墨小楼MC1002
icon.png[分享] 丹龙隔热纸GE55+33+22
icon.png[问题] 清洗洗衣机
icon.png[寻物] 窗台下的空间
icon.png[闲聊] 双极の女神1 木魔爵
icon.png[售车] 新竹 1997 march 1297cc 白色 四门
icon.png[讨论] 能从照片感受到摄影者心情吗
icon.png[狂贺] 贺贺贺贺 贺!岛村卯月!总选举NO.1
icon.png[难过] 羡慕白皮肤的女生
icon.png阅读文章
icon.png[黑特]
icon.png[问题] SBK S1安装於安全帽位置
icon.png[分享] 旧woo100绝版开箱!!
icon.pngRe: [无言] 关於小包卫生纸
icon.png[开箱] E5-2683V3 RX480Strix 快睿C1 简单测试
icon.png[心得] 苍の海贼龙 地狱 执行者16PT
icon.png[售车] 1999年Virage iO 1.8EXi
icon.png[心得] 挑战33 LV10 狮子座pt solo
icon.png[闲聊] 手把手教你不被桶之新手主购教学
icon.png[分享] Civic Type R 量产版官方照无预警流出
icon.png[售车] Golf 4 2.0 银色 自排
icon.png[出售] Graco提篮汽座(有底座)2000元诚可议
icon.png[问题] 请问补牙材质掉了还能再补吗?(台中半年内
icon.png[问题] 44th 单曲 生写竟然都给重复的啊啊!
icon.png[心得] 华南红卡/icash 核卡
icon.png[问题] 拔牙矫正这样正常吗
icon.png[赠送] 老莫高业 初业 102年版
icon.png[情报] 三大行动支付 本季掀战火
icon.png[宝宝] 博客来Amos水蜡笔5/1特价五折
icon.pngRe: [心得] 新鲜人一些面试分享
icon.png[心得] 苍の海贼龙 地狱 麒麟25PT
icon.pngRe: [闲聊] (君の名は。雷慎入) 君名二创漫画翻译
icon.pngRe: [闲聊] OGN中场影片:失踪人口局 (英文字幕)
icon.png[问题] 台湾大哥大4G讯号差
icon.png[出售] [全国]全新千寻侘草LED灯, 水草

请输入看板名称,例如:iOS站内搜寻

TOP