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

  • 相关阅读:
    python 全栈基础作业题
    计算机基础之二:操作系统的发展史
    计算机基础系列之一:计算机硬件概述
    饼图
    折线图
    win_diy_monkey demo
    csv,Excel
    uiautomator2
    win ui自动化测试
    html
  • 原文地址:https://www.cnblogs.com/ainima/p/6331350.html
Copyright © 2011-2022 走看看