zoukankan      html  css  js  c++  java
  • Java中HashMap,Hashtable和LinkedList

    今天碰到一个很有意思的问题,就是关于使用LinkedList作为HashMap或者Hashtable得key,但是最后发现数据并没有存进去。

    首先说一下HashMap,Hashtable吧,它们都继承了Cloneable, Map, Serializable。它们两个基本上是一样的,“The HashMap class is roughly equivalent to Hashtable , except that it is unsynchronized and permits nulls.”。区别就是HashMap允许“ null values and the null key”,同时 unsynchronized。它的性能取决于“ initial capacity and load factor ”,具体参考官方文档。HashMap还有一个特性就是不能保证存入的元素的顺序,“HashMap does not guarantee that the order will remain constant over time。” 对于存入到里面的key,要求“To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. ”。更具我的测试,其实这个对于HashMap也是适用的。

    这个就和我今天碰到的问题联系上了,LinkedList类里面的hashCode()函数来源于List.hashCode(),具体如下:

    也就是说hashCode依赖于内部存储的对象,恰好我存储的是一个抽象类,以方便实现多态性,所以并没有实现hashCode函数。如果存储的是类似String的基本数据类型或者是实现了hashCode函数的对象就可以了。

    最后还有一个和HashMap有点容易混淆的类就是TreeMap。它继承了“Serializable, Cloneable, Map<K,V>, SortedMap<K,V>”,是SortedMap接口类唯一的实现。它本质上是“Red-Black tree”,里面存储的key是升序排列的,“ascending key order”。

    参考:

    http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html

    http://java.sun.com/j2se/1.4.2/docs/api/java/util/Hashtable.html

    http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html

    http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html

    http://java.sun.com/j2se/1.5.0/docs/api/java/util/SortedMap.html

  • 相关阅读:
    Qt中暂停线程的执行(主线程和工作线程共用一把锁,一旦主线程将它锁上,工作线程就无法运行了,这也是一个办法)
    罗振宇 知识就是力量:怎样逼自己成为一个上进的人
    GammaRay 是一个允许你查看 Qt 应用程序甚至在某种程度上修改它的独特应用,可谓是 Debugger 的良好补充
    VSCode高效开发插件
    微软白板Excel xls列号数字转字母
    如何渡过中年危机
    增量数据同步中间件
    N位N进制里有多少个N
    Orchard Core学习一
    Consul做服务发现
  • 原文地址:https://www.cnblogs.com/ainima/p/6331350.html
Copyright © 2011-2022 走看看