各种集合类型底层实现原理

①HashMap的工作原理

HashMap基于hashing原理,我们通过put()和get()方法储存和获取对象。当我们将键值对传递给put()方法时,它调用键对象的hashCode()方法来计算hashcode,让后找到bucket位置来储存值对象。当获取对象时,通过键对象的equals()方法找到正确的键值对,然后返回值对象。HashMap使用链表来解决碰撞问题,当发生碰撞了,对象将会储存在链表的下一个节点中。 HashMap在每个链表节点中储存键值对对象。

当两个不同的键对象的hashcode相同时会发生什么? 它们会储存在同一个bucket位置的链表中。键对象的equals()方法用来找到键值对。

因为HashMap的好处非常多,我曾经在电子商务的应用中使用HashMap作为缓存。因为金融领域非常多的运用Java,也出于性能的考虑,我们会经常用到HashMap和ConcurrentHashMap。
HashMap底层是用数组链表存储的,元素是Entry。向HashMap添加时,由key的hashcode决定Entry存储位置,当两个Entry对象的key的hashcode相同时,由key的equals()方法返回值决定采用覆盖行为(返回true),还是在链表头添加新的Entry(返回false)。Collection values(),返回集合对象,但不能添加元素,主要是用来遍历。自定义类如果放入HashMap或HashSet中,需要重写equals和hashcode方法。

<h1>
    <span class="link_title"><a href="/lyp0715/article/details/50553345">
    各种集合类型底层实现原理&amp;nbsp;&amp;nbsp;泽0715…            
    </a></span>
</h1>
    <div class="article_manage clearfix">
    <div class="article_r">
        <span class="link_postdate">2016-01-21 10:21</span>
        <span class="link_view" title="阅读次数">1628人阅读</span>
        <span class="link_comments" title="评论次数"> <a href="#comments" onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_pinglun'])">评论</a>(1)</span>
        <span class="link_collect tracking-ad" data-mod="popu_171"> <a href="javascript:void(0);" onclick="javascript:collectArticle('%e5%90%84%e7%a7%8d%e9%9b%86%e5%90%88%e7%b1%bb%e5%9e%8b%e5%ba%95%e5%b1%82%e5%ae%9e%e7%8e%b0%e5%8e%9f%e7%90%86%26nbsp%3b%26nbsp%3b%e6%b3%bd0715%e2%80%a6','50553345');return false;" title="收藏" target="_blank">收藏</a></span>
         <span class="link_report"> <a href="#report" onclick="javascript:report(50553345,2);return false;" title="举报">举报</a></span>

    </div>
</div>
<div class="embody" style="display:none" id="embody">
    <span class="embody_t">本文章已收录于:</span>
    <div class="embody_c" id="lib" value="{&quot;err&quot;:0,&quot;msg&quot;:&quot;ok&quot;,&quot;data&quot;:[]}"></div>
</div>
<style type="text/css">        
        .embody{
            padding:10px 10px 10px;
            margin:0 -20px;
            border-bottom:solid 1px #ededed;                
        }
        .embody_b{
            margin:0 ;
            padding:10px 0;
        }
        .embody .embody_t,.embody .embody_c{
            display: inline-block;
            margin-right:10px;
        }
        .embody_t{
            font-size: 12px;
            color:#999;
        }
        .embody_c{
            font-size: 12px;
        }
        .embody_c img,.embody_c em{
            display: inline-block;
            vertical-align: middle;               
        }
         .embody_c img{               
            width:30px;
            height:30px;
        }
        .embody_c em{
            margin: 0 20px 0 10px;
            color:#333;
            font-style: normal;
        }
</style>
<script type="text/javascript">
    $(function () {
        try
        {
            var lib = eval("("+$("#lib").attr("value")+")");
            var html = "";
            if (lib.err == 0) {
                $.each(lib.data, function (i) {
                    var obj = lib.data[i];
                    //html += '<img src="' + obj.logo + '"/>' + obj.name + "&nbsp;&nbsp;";
                    html += ' <a href="' + obj.url + '" target="_blank">';
                    html += ' <img src="' + obj.logo + '">';
                    html += ' <em><b>' + obj.name + '</b></em>';
                    html += ' </a>';
                });
                if (html != "") {
                    setTimeout(function () {
                        $("#lib").html(html);                      
                        $("#embody").show();
                    }, 100);
                }
            }      
        } catch (err)
        { }
        
    });
</script>
<script type="text/javascript" src="http://static.blog.csdn.net/scripts/category.js"></script>  
    <div class="bog_copyright">         
        <p class="copyright_p">版权声明:本文为博主原创文章,未经博主允许不得转载。</p>
    </div>

Set和Map的关系
Set代表无序,不能重复的集合;Map代表Key-Value组成的集合,是一种关联数组。Map的Key要求是不能重复,没有顺序。把Map的所有Key组合起来就是Set。Set keySet();


HashMap和HashSet原理
HashMap底层是用数组链表存储的,元素是Entry。向HashMap添加时,由key的hashcode决定Entry存储位置,当两个Entry对象的key的hashcode相同时,由key的equals()方法返回值决定采用覆盖行为(返回true),还是在链表头添加新的Entry(返回false)。Collection values(),返回集合对象,但不能添加元素,主要是用来遍历。自定义类如果放入HashMap或HashSet中,需要重写equals和hashcode方法。

 

HashSet s = new HashSet

s.add(new Name("1"));

System.out.println(s.contains(new Name("1")));


如果不对Name类重写hashcode,equals,输出结果是false。因为默认的不能保证结果一样。



TreeMap和TreeSet原理
TreeMap底层是用红黑树来存储,每个Entry对应树的一个节点,TreeMap元素默认从小到大排序。V put(Key k, Value v)实质是二叉排序树的插入算法

ArrayList底层是数组
List是线性表的数据结构,ArrayList是顺序存储的线性表

LinkedList底层是链表
LinkedList是链式存储的线性表,实质是双向链表,实现了List和Deque接口。Deque代表双端队列,既可以当做队列也可以当作栈。

Vector和ArrayList区别
Vector提供synchronized修饰方法,是线程安全版本的ArrayList
.Vector 本质是一个数组,其实所有集合都是数组,从JAVA 来说搞成了对象,符合我  们的OO,可以参考学习。
Iterator迭代器
用于迭代Collection集合,包括Set和List。集合提供iterator()方法
迭代器模式:系统为遍历集合提供标准的“迭代器接口”,用于访问集合里的数据,如何实现交给集合自己完成。
    <div id="digg" articleid="50553345">
        <dl id="btnDigg" class="digg digg_disable" onclick="btndigga();">
           
             <dt>顶</dt>
            <dd>1</dd>
        </dl>
       
          
        <dl id="btnBury" class="digg digg_disable" onclick="btnburya();">
          
              <dt>踩</dt>
            <dd>0</dd>               
        </dl>
        
    </div>
 <div class="tracking-ad" data-mod="popu_222"><a href="javascript:void(0);" target="_blank">&nbsp;</a>   </div>
<div class="tracking-ad" data-mod="popu_223"> <a href="javascript:void(0);" target="_blank">&nbsp;</a></div>
<script type="text/javascript">
            function btndigga() {
                $(".tracking-ad[data-mod='popu_222'] a").click();
            }
            function btnburya() {
                $(".tracking-ad[data-mod='popu_223'] a").click();
            }
        </script>
<div style="clear:both; height:10px;"></div>
 <div>
         <div class="J_adv" data-view="true" data-mod="ad_popu_206" data-mtp="43" data-order="114" data-con="ad_content_1901" style="width: 960px; height: 90px;"><script src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><ins class="adsbygoogle" style="display:inline-block;width:960px;height:90px" data-ad-client="ca-pub-8990951720398508" data-ad-slot="8267689356/3776917242" data-adsbygoogle-status="done"><ins id="aswift_0_expand" style="display:inline-table;border:none;height:90px;margin:0;padding:0;position:relative;visibility:visible;width:960px;background-color:transparent"><ins id="aswift_0_anchor" style="display:block;border:none;height:90px;margin:0;padding:0;position:relative;visibility:visible;width:960px;background-color:transparent"><iframe width="960" height="90" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" onload="var i=this.id,s=window.google_iframe_oncopy,H=s&amp;&amp;s.handlers,h=H&amp;&amp;H[i],w=this.contentWindow,d;try{d=w.document}catch(e){}if(h&amp;&amp;d&amp;&amp;(!d.body||!d.body.firstChild)){if(h.call){setTimeout(h,0)}else if(h.match){try{h=s.upd(h,i)}catch(e){}w.location.replace(h)}}" id="aswift_0" name="aswift_0" style="left:0;position:absolute;top:0;"></iframe></ins></ins></ins><script>(adsbygoogle=window.adsbygoogle || []).push({});</script></div> 
</div>

参考知识库

img

Java SE知识库

img

Java EE知识库

img

Java 知识库

img

算法与数据结构知识库

 <dt><span>猜你在找</span></dt>    





<div id="adCollege" style="width: 42%;float: left;"> 
    <script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script> 
    <script type="text/javascript">
        csdn.position.showEdu({
            sourceType: "blog",
            searchType: "detail",
            searchKey: "50553345",
            username: "",
            recordcount: "5",
            containerId: "adCollege" //容器DIV的id。 
        });
    </script> 
<div class="tracking-ad" data-mod="popu_84"><dd style="background:url(http://static.blog.csdn.net/skin/default/images/blog-dot-red3.gif) no-repeat 0 10px; white-space: nowrap;"><a href="http://edu.csdn.net/course/detail/1487" title="Ceph—分布式存储系统的另一个选择" strategy="v4:content" target="_blank">Ceph—分布式存储系统的另一个选择</a></dd><dd style="background:url(http://static.blog.csdn.net/skin/default/images/blog-dot-red3.gif) no-repeat 0 10px; white-space: nowrap;"><a href="http://edu.csdn.net/course/detail/2513" title="顾荣:开源大数据存储系统Alluxio(原Tachyon)的原理分析与案例简介" strategy="v4:content" target="_blank">顾荣:开源大数据存储系统Alluxio(原Tachyon)的原理分析与案例简介</a></dd><dd style="background:url(http://static.blog.csdn.net/skin/default/images/blog-dot-red3.gif) no-repeat 0 10px; white-space: nowrap;"><a href="http://edu.csdn.net/course/detail/550" title="CCIE专家讲解思科认证网络认证CCNA v2.0网络工程师和网络安全课程" strategy="v4:content" target="_blank">CCIE专家讲解思科认证网络认证CCNA v2.0网络工程师和网络安全课程</a></dd><dd style="background:url(http://static.blog.csdn.net/skin/default/images/blog-dot-red3.gif) no-repeat 0 10px; white-space: nowrap;"><a href="http://edu.csdn.net/course/detail/3004" title="Android之数据存储" strategy="v4:content" target="_blank">Android之数据存储</a></dd><dd style="background:url(http://static.blog.csdn.net/skin/default/images/blog-dot-red3.gif) no-repeat 0 10px; white-space: nowrap;"><a href="http://edu.csdn.net/course/detail/1512" title="数据结构基础系列(5):数组与广义表" strategy="v4:content" target="_blank">数据结构基础系列(5):数组与广义表</a></dd></div></div>  


 <div id="res" data-mod="popu_36" class="tracking-ad" style="width: 42%; float: left; margin-right: 30px; display: block;"><dd style="background:url(http://static.blog.csdn.net/skin/default/images/blog-dot-red3.gif) no-repeat 0 10px;"><a href="http://blog.csdn.net/orz365/article/details/9236045" title="转emacs&amp;nbspTAB&amp;空格缩进配置命令" strategy="SearchAlgorithm" target="_blank">转emacs&nbsp;TAB&amp;空格缩进配置命令</a></dd><dd style="background:url(http://static.blog.csdn.net/skin/default/images/blog-dot-red3.gif) no-repeat 0 10px;"><a href="http://blog.csdn.net/baohanqing/article/details/17689097" title="jsjavascript正则表达式中g&amp;ampnbsp" strategy="SearchAlgorithm" target="_blank">jsjavascript正则表达式中g&amp;nbsp</a></dd><dd style="background:url(http://static.blog.csdn.net/skin/default/images/blog-dot-red3.gif) no-repeat 0 10px;"><a href="http://blog.csdn.net/victortony/article/details/38459509" title="Eclipse&nbsp;警告提示Access&amp;ampnb" strategy="SearchAlgorithm" target="_blank">Eclipse&nbsp;警告提示Access&amp;nb</a></dd><dd style="background:url(http://static.blog.csdn.net/skin/default/images/blog-dot-red3.gif) no-repeat 0 10px;"><a href="http://blog.csdn.net/haoge7777/article/details/50605584" title="libnumaso164bit&amp;nbspis&amp;ampnb" strategy="SearchAlgorithm" target="_blank">libnumaso164bit&nbsp;is&amp;nb</a></dd><dd style="background:url(http://static.blog.csdn.net/skin/default/images/blog-dot-red3.gif) no-repeat 0 10px;"><a href="http://blog.csdn.net/senlinmu110/article/details/52042680" title="ALV&amp;nbspdemocl_salv_table&amp;ampnbs" strategy="SearchAlgorithm" target="_blank">ALV&nbsp;democl_salv_table&amp;nbs</a></dd></div>
<div id="ad_cen">        
                  <div class="J_adv" data-view="true" data-mod="ad_popu_199" data-mtp="43" data-order="114" data-con="ad_content_1843" style="width: 960px; height: 90px;"><script src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><ins class="adsbygoogle" style="display:inline-block;width:960px;height:90px" data-ad-client="ca-pub-8990951720398508" data-ad-slot="8267689356/3115746762" data-adsbygoogle-status="done"><ins id="aswift_1_expand" style="display:inline-table;border:none;height:90px;margin:0;padding:0;position:relative;visibility:visible;width:960px;background-color:transparent"><ins id="aswift_1_anchor" style="display:block;border:none;height:90px;margin:0;padding:0;position:relative;visibility:visible;width:960px;background-color:transparent"><iframe width="960" height="90" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" onload="var i=this.id,s=window.google_iframe_oncopy,H=s&amp;&amp;s.handlers,h=H&amp;&amp;H[i],w=this.contentWindow,d;try{d=w.document}catch(e){}if(h&amp;&amp;d&amp;&amp;(!d.body||!d.body.firstChild)){if(h.call){setTimeout(h,0)}else if(h.match){try{h=s.upd(h,i)}catch(e){}w.location.replace(h)}}" id="aswift_1" name="aswift_1" style="left:0;position:absolute;top:0;"></iframe></ins></ins></ins><script>(adsbygoogle=window.adsbygoogle || []).push({});</script></div>
</div>  

<!-- 广告位开始 -->
<div class="J_adv" data-view="true" data-mod="ad_popu_72" data-mtp="61" data-order="114" data-con="ad_content_1937"><script id="popuLayer_js_q" src="http://ads.csdn.net/js/popuLayer.js" defer="" type="text/javascript"></script><div id="location_parent_google"></div><script src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><div id="layerd_google" style="position: fixed; bottom: 0px; right: 0px; line-height: 0px; z-index: 1000; width: 302px; height: 275px; display: none;"><div class="J_close layer_close" style="display:;background-color:#efefef;padding:0px;color:#333;font:12px/24px Helvetica,Tahoma,Arial,sans-serif;text-align:right;">关闭</div><ins class="adsbygoogle" style="display: inline-block; width: 300px; height: 250px;" data-ad-client="ca-pub-8990951720398508" data-ad-slot="8267689356/2658895482" data-adsbygoogle-status="done"><ins id="aswift_2_expand" style="display:inline-table;border:none;height:250px;margin:0;padding:0;position:relative;visibility:visible;width:300px;background-color:transparent"><ins id="aswift_2_anchor" style="display:block;border:none;height:250px;margin:0;padding:0;position:relative;visibility:visible;width:300px;background-color:transparent"><iframe width="300" height="250" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" onload="var i=this.id,s=window.google_iframe_oncopy,H=s&amp;&amp;s.handlers,h=H&amp;&amp;H[i],w=this.contentWindow,d;try{d=w.document}catch(e){}if(h&amp;&amp;d&amp;&amp;(!d.body||!d.body.firstChild)){if(h.call){setTimeout(h,0)}else if(h.match){try{h=s.upd(h,i)}catch(e){}w.location.replace(h)}}" id="aswift_2" name="aswift_2" style="left:0;position:absolute;top:0;"></iframe></ins></ins></ins></div><script>(adsbygoogle=window.adsbygoogle || []).push({});</script><script>  document.getElementById('popuLayer_js_q').onload=function(){      var styObjd=styObj={width:'302px',height:'275px'};window.CSDN.Layer.PopuLayer('#layerd_google',{storageName:'layerd',styleObj:styObjd,total:50,expoire:1000*60});  }</script></div>
<!-- 广告位结束 -->
查看评论
1楼 丁国华 2016-12-07 11:36发表 [回复]
mark
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
<div id="ad_bot">
</div>
    <a id="quick-reply" class="btn btn-top q-reply" title="快速回复" style="display:none;">
        <img src="http://static.blog.csdn.net/images/blog-icon-reply.png" alt="快速回复">
    </a>    
<a id="d-top-a" class="btn btn-top backtop" style="display: none;" title="返回顶部" onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_huidaodingbu'])">         
     <img src="http://static.blog.csdn.net/images/top.png" alt="TOP">
</a>

                    <div class="clear">
                    </div>
                </div>
posted @ 2017-01-16 10:48  jobs-lgy  阅读(446)  评论(0编辑  收藏  举报