开发者社区> 问答> 正文

Java中HashMap关键字transient的疑惑

HashMap中有个对象 transient Entry[] table;这个是存储数据的地方,但是为什么要加上关键字transient呢
对于transient的解释
transient是Java语言的关键字,用来表示一个域不是该对象串行化的一部分。当一个对象被串行化的时候,transient型变量的值不包括在串行化的表示中,也就是说没法持久化。
那么这种设计为什么用在HashMap中呢?有什么用意

展开
收起
蛮大人123 2016-02-29 17:27:00 4492 0
2 条回答
写回答
取消 提交回答
  • 为了安全起见,不希望在网络操作(主要涉及到序列化操作,本地序列化缓存也适用)中被传输,这些信息对应的变量就可以加上transient关键字。 https://www.cnblogs.com/lanxuezaipiao/p/3369962.html
    2019-07-17 18:50:39
    赞同 展开评论 打赏
  • 我说我不帅他们就打我,还说我虚伪

    For example, consider the case of a hash table. The physical
    representation is a sequence of hash buckets containing key-value

    1. The bucket that an entry resides in is a function of the hash
    2. of its key, which is not, in general, guaranteed to be the same

    from JVM implementation to JVM implementation. In fact, it isn't even
    guaranteed to be the same from run to run. Therefore, accepting the
    default serialized form for a hash table would constitute a serious

    1. Serializing and deserializing the hash table could yield an
      object whose invariants were seriously corrupt.

    怎么理解? 看一下HashMap.get()/put()知道, 读写Map是根据Object.hashcode()来确定从哪个bucket读/写. 而Object.hashcode()是native方法, 不同的JVM里可能是不一样的.

    打个比方说, 向HashMap存一个entry, key为 字符串"STRING", 在第一个java程序里, "STRING"的hashcode()为1, 存入第1号bucket; 在第二个java程序里, "STRING"的hashcode()有可能就是2, 存入第2号bucket. 如果用默认的串行化(Entry[] table不用transient), 那么这个HashMap从第一个java程序里通过串行化导入第二个java程序后, 其内存分布是一样的. 这就不对了. HashMap现在的readObject和writeObject是把内容 输出/输入, 把HashMap重新生成出来.

    2019-07-17 18:50:39
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载