V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
lxk11153
V2EX  ›  Java

Java .lang.String#value 从 char[]变到 byte[]有啥用意吗?

  •  
  •   lxk11153 · 2020-04-06 04:51:33 +08:00 · 2383 次点击
    这是一个创建于 1694 天前的主题,其中的信息可能已经有所发展或是发生改变。
    # java 8
    public final class String
        implements java.io.Serializable, Comparable<String>, CharSequence {
        /** The value is used for character storage. */
        private final char value[];
    
    # java 10
    public final class String
        implements java.io.Serializable, Comparable<String>, CharSequence {
        /**
         * The value is used for character storage.
         *
         * @implNote This field is trusted by the VM, and is a subject to
         * constant folding if String instance is constant. Overwriting this
         * field after construction will cause problems.
         *
         * Additionally, it is marked with {@link Stable} to trust the contents
         * of the array. No other facility in JDK provides this functionality (yet).
         * {@link Stable} is safe here, because value is never null.
         */
        @Stable
        private final byte[] value;
    

    ps: 不知道哪个版本变的,没去看 java 9

    3 条回复    2020-04-22 15:47:51 +08:00
    shiyouming91
        1
    shiyouming91  
       2020-04-06 08:30:50 +08:00   ❤️ 4
    Java 9 引入的 Compact Strings 。主要是为了节省内存。当构造的 String 每个字符都可以用 1 byte 表示的时候,会自动在内部存成每个字符 1 byte,不然像原来一样存成每个字符 2 bytes 。

    https://www.vojtechruzicka.com/java-9-compact-strings/
    Aresxue
        2
    Aresxue  
       2020-04-07 09:17:03 +08:00
    更省内存呗。。。用 jol 打印下内存布局就知道,以前 Java 主要考虑易用性,现在开始优化语法糖和内存了,变成更好的语言吧
    lxk11153
        3
    lxk11153  
    OP
       2020-04-22 15:47:51 +08:00
    @shiyouming91 #1 那里面说的"Depending on which characters it contains, it will either use UTF-16 or Latin-1, that is - either one or two bytes per character."
    是不是有点问题啊? Latin-1: one byte per character 没问题
    UTF-16 是 two bytes per character 吗?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5662 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 06:46 · PVG 14:46 · LAX 22:46 · JFK 01:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.