Home > Java > javaTutorial > body text

Comprehensive analysis of the contents of the Java String class (with code)

不言
Release: 2018-09-15 16:55:31
Original
2063 people have browsed it

The content this article brings to you is about the comprehensive analysis of the Java String class (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In the past year since I started writing Java, I have been trying to solve any problems I encountered. I have not taken the initiative to learn the features of the Java language in depth or read the source code of the JDK in depth. Since you have decided to rely on Java
for a living in the future, you still have to put some thought into it, give up some time playing games, and study the system in depth.

Java String is one of the most commonly used classes in Java programming and the most basic class provided by the JDK. So I decided to start with the String class and study it in depth to get a good start.

Class definition and class members

Open the String source code in the JDK, and you should first pay attention to the definition of the String class.

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence
Copy after login

Non-inheritable and immutable

Anyone who has written Java knows that when the final keyword modifies a class, it means that this class is not inheritable. Therefore, the String class cannot be inherited externally. At this time we may be curious why the designer of String designed it to be non-inheritable. I found related questions and discussions on Zhihu,
I think the first answer has made it very clear. As the most basic reference data type of Java, the most important point of String is immutability, so using final is to **forbid inheritance
which destroys the immutable nature of String**.

To achieve the immutability of a class, it is not just as simple as using final to modify the class. From the source code, we can see that String is actually an encapsulation of a character array, and the character array is private and does not provide

Any method that can modify the character array, so once initialization is completed, the String object cannot be modified.

Serialization

From the above class definition, we see that String implements the serialization interface Serializable, so String supports serialization and deserialization.

What is serialization of Java objects? I believe many Java noobs like me have this question. In-depth analysis of Java serialization and deserialization This paragraph in this article
explains it very well.
The Java platform allows us to create reusable Java objects in memory, but in general,

These objects may only exist when the JVM is running,
That is, the life cycle of these objects does not It will have a longer life cycle than the JVM. But in real applications,
may require that the specified object can be saved (persisted) after the JVM stops running, and the saved object can be re-read in the future.
Java object serialization can help us achieve this function.
Using Java object serialization, when saving an object, its state will be saved as a set of bytes, and in the future, these bytes will be assembled into objects.
It must be noted that object serialization saves the "state" of the object, that is, its member variables. It can be seen that object serialization does not pay attention to static variables in the class.
In addition to object serialization being used when persisting objects, object serialization is also used when using RMI (remote method invocation) or passing objects over the network.
Java Serialization API provides a standard mechanism for handling object serialization. The API is simple and easy to use.
In the String source code, we can also see class member definitions that support serialization.

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;

    /**
     * Class String is special cased within the Serialization Stream Protocol.
     *
     * A String instance is written into an ObjectOutputStream according to
     * <a href="{@docRoot}/../platform/serialization/spec/output.html">
     * Object Serialization Specification, Section 6.2, "Stream Elements"</a>
     */
    private static final ObjectStreamField[] serialPersistentFields =
        new ObjectStreamField[0];
Copy after login
serialVersionUID is a serialization version number. Java uses this UID to determine the consistency of the byte stream during deserialization and the local class. If they are the same, they are considered consistent and

can be deserialized. , an exception will be thrown if different.

serialPersistentFields This definition is much rarer than the previous one. It is probably related to the class members during serialization. In order to understand the meaning of this field, I Googled Baidu and

only found a little description of the class ObjectStreamField in the JDK document, `A description of a Serializable field from a Serializable class.
An array of ObjectStreamFields is used to declare the Serializable fields of a class.` The general idea is that this class is used to describe a serialized field of the serialized class.
If you define an array of this type, you can declare the fields that the class needs to be serialized. But I still haven’t found the specific usage and function of this class. Later, I took a closer look at the definition of this field.
and serialVersionUID should also define various rules through specific field names. Then I directly searched for the keyword serialPersistentFields and finally found its specific role.
That is, **default serialization customization includes the keyword transient and the static field name serialPersistentFields. transient is used to specify which fields are not serialized by default.
serialPersistentFields is used to specify which fields need to be serialized by default. If both serialPersistentFields and transient are defined, transient will be ignored. **
I also tested it myself, and it does have this effect.

知道了 serialPersistentFields 的作用以后,问题又来了,既然这个静态字段是用来定义参与序列化的类成员的,那为什么在 String 中这个数组的长度定义为0?
经过一番搜索查找资料以后,还是没有找到一个明确的解释,期待如果有大佬看到能解答一下。

可排序

String 类还实现了 Comparable 接口,Comparable接口只有一个方法 public int compareTo(T o),实现了这个接口就意味着该类支持排序,
即可用 Collections.sort 或 Arrays.sort 等方法对该类的对象列表或数组进行排序。

在 String 中我们还可以看到这样一个静态变量,

 public static final Comparator<String> CASE_INSENSITIVE_ORDER
                                         = new CaseInsensitiveComparator();
private static class CaseInsensitiveComparator
            implements Comparator<String>, java.io.Serializable {
        // use serialVersionUID from JDK 1.2.2 for interoperability
        private static final long serialVersionUID = 8575799808933029326L;

        public int compare(String s1, String s2) {
            int n1 = s1.length();
            int n2 = s2.length();
            int min = Math.min(n1, n2);
            for (int i = 0; i < min; i++) {
                char c1 = s1.charAt(i);
                char c2 = s2.charAt(i);
                if (c1 != c2) {
                    c1 = Character.toUpperCase(c1);
                    c2 = Character.toUpperCase(c2);
                    if (c1 != c2) {
                        c1 = Character.toLowerCase(c1);
                        c2 = Character.toLowerCase(c2);
                        if (c1 != c2) {
                            // No overflow because of numeric promotion
                            return c1 - c2;
                        }
                    }
                }
            }
            return n1 - n2;
        }

        /** Replaces the de-serialized object. */
        private Object readResolve() { return CASE_INSENSITIVE_ORDER; }
    }
Copy after login

从上面的源码中可以看出,这个静态成员是一个实现了 Comparator 接口的类的实例,而实现这个类的作用是比较两个忽略大小写的 String 的大小。

那么 Comparable 和 Comparator 有什么区别和联系呢?同时 String 又为什么要两个都实现一遍呢?

第一个问题这里就不展开了,总结一下就是,Comparable 是类的内部实现,一个类能且只能实现一次,而 Comparator 则是外部实现,可以通过不改变
类本身的情况下,为类增加更多的排序功能。
所以我们也可以为 String 实现一个 Comparator使用。

String 实现了两种比较方法的意图,实际上是一目了然的。实现 Comparable 接口为类提供了标准的排序方案,同时为了满足大多数排序需求的忽略大小写排序的情况,
String 再提供一个 Comparator 到公共静态类成员中。如果还有其他的需求,那就只能我们自己实现了。

类方法

String 的方法大致可以分为以下几类。

  • 构造方法

  • 功能方法

  • 工厂方法

  • intern方法

关于 String 的方法的解析,这篇文章已经解析的够好了,所以我这里也不再重复的说一遍了。不过
最后的 intern 方法值得我们去研究。

intern方法

字符串常量池

String 做为 Java 的基础类型之一,可以使用字面量的形式去创建对象,例如 String s = "hello"。当然也可以使用 new 去创建 String 的对象,
但是几乎很少看到这样的写法,久而久之我便习惯了第一种写法,但是却不知道背后大有学问。下面一段代码可以看出他们的区别。

public class StringConstPool {
    public static void main(String[] args) {
        String s1 = "hello world";
        String s2 = new String("hello world");
        String s3 = "hello world";
        String s4 = new String("hello world");
        String s5 = "hello " + "world";
        String s6 = "hel" + "lo world";
        String s7 = "hello";
        String s8 = s7 + " world";
        
        System.out.println("s1 == s2: " + String.valueOf(s1 == s2) );
        System.out.println("s1.equals(s2): " + String.valueOf(s1.equals(s2)));
        System.out.println("s1 == s3: " + String.valueOf(s1 == s3));
        System.out.println("s1.equals(s3): " + String.valueOf(s1.equals(s3)));
        System.out.println("s2 == s4: " + String.valueOf(s2 == s4));
        System.out.println("s2.equals(s4): " + String.valueOf(s2.equals(s4)));
        System.out.println("s5 == s6: " + String.valueOf(s5 == s6));
        System.out.println("s1 == s8: " + String.valueOf(s1 == s8));
    }
}
/* output
s1 == s2: false
s1.equals(s2): true
s1 == s3: true
s1.equals(s3): true
s2 == s4: false
s2.equls(s4): true
s5 == s6: true
s1 == s8: false
 */
Copy after login

从这段代码的输出可以看到,equals 比较的结果都是 true,这是因为 String 的 equals 比较的值( Object 对象的默认 equals 实现是比较引用,
String 对此方法进行了重写)。== 比较的是两个对象的引用,如果引用相同则返回 true,否则返回 false。s1==s2: false和 s2==s4: false
说明了 new 一个对象一定会生成一个新的引用返回。s1==s3: true 则证明了使用字面量创建对象同样的字面量会得到同样的引用。

s5 == s6 实际上和 s1 == s3 在 JVM 眼里是一样的情况,因为早在编译阶段,这种常量的简单运算就已经完成了。我们可以使用 javap 反编译一下 class 文件去查看
编译后的情况。

➜ ~ javap -c StringConstPool.class
Compiled from "StringConstPool.java"
public class io.github.jshanet.thinkinginjava.constpool.StringConstPool {
  public io.github.jshanet.thinkinginjava.constpool.StringConstPool();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: ldc           #2                  // String hello world
       2: astore_1
       3: return
}
Copy after login

看不懂汇编也没关系,因为注释已经很清楚了......

s1 == s8 的情况就略复杂,s8 是通过变量的运算而得,所以无法在编译时直接算出其值。而 Java 又不能重载运算符,所以我们在 JDK 的源码里也
找不到相关的线索。万事不绝反编译,我们再通过反编译看看实际上编译器对此是否有影响。

public class io.github.jshanet.thinkinginjava.constpool.StringConstPool {
  public io.github.jshanet.thinkinginjava.constpool.StringConstPool();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: ldc           #2                  // String hello
       2: astore_1
       3: new           #3                  // class java/lang/StringBuilder
       6: dup
       7: invokespecial #4                  // Method java/lang/StringBuilder."<init>":()V
      10: aload_1
      11: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      14: ldc           #6                  // String  world
      16: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      19: invokevirtual #7                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      22: astore_2
      23: return
}
Copy after login

通过反编译的结果可以发现,String 的变量运算实际上在编译后是由 StringBuilder 实现的,s8 = s7 + " world" 的代码等价于
(new StringBuilder(s7)).append(" world").toString()。Stringbuilder 是可变的类,通过 append 方法 和 toString 将两个 String 对象聚合
成一个新的 String 对象,所以到这里就不难理解为什么 s1 == s8 : false 了。

之所以会有以上的效果,是因为有字符串常量池的存在。字符串对象的分配和其他对象一样是要付出时间和空间代价,而字符串又是程序中最常用的对象,JVM
为了提高性能和减少内存占用,引入了字符串的常量池,在使用字面量创建对象时, JVM 首先会去检查常量池,如果池中有现成的对象就直接返回它的引用,如果
没有就创建一个对象,并放到池里。因为字符串不可变的特性,所以 JVM 不用担心多个变量引用同一个对象会改变对象的状态。同时运行时实例创建的全局
字符串常量池中有一个表,总是为池中的每个字符串对象维护一个引用,所以这些对象不会被 GC 。

intern 方法的作用

上面说了很多都没有涉及到主题 intern 方法,那么 intern 方法到作用到底是什么呢?首先查看一下源码。

    /**
     * Returns a canonical representation for the string object.
     * <p>
     * A pool of strings, initially empty, is maintained privately by the
     * class {@code String}.
     * <p>
     * When the intern method is invoked, if the pool already contains a
     * string equal to this {@code String} object as determined by
     * the {@link #equals(Object)} method, then the string from the pool is
     * returned. Otherwise, this {@code String} object is added to the
     * pool and a reference to this {@code String} object is returned.
     * <p>
     * It follows that for any two strings {@code s} and {@code t},
     * {@code s.intern() == t.intern()} is {@code true}
     * if and only if {@code s.equals(t)} is {@code true}.
     * <p>
     * All literal strings and string-valued constant expressions are
     * interned. String literals are defined in section 3.10.5 of the
     * <cite>The Java&trade; Language Specification</cite>.
     *
     * @return  a string that has the same contents as this string, but is
     *          guaranteed to be from a pool of unique strings.
     */
    public native String intern();
Copy after login

Oracle JDK 中,intern 方法被 native 关键字修饰并且没有实现,这意味着这部分到实现是隐藏起来了。从注释中看到,这个方法的作用是如果常量池
中存在当前字符串,就会直接返回当前字符串,如果常量池中没有此字符串,会将此字符串放入常量池中后再返回。通过注释的介绍已经可以明白这个方法的作用了,
再用几个例子证明一下。

public class StringConstPool {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = new String("hello");
        String s3 = s2.intern();
        System.out.println("s1 == s2: " + String.valueOf(s1 == s2));
        System.out.println("s1 == s3: " + String.valueOf(s1 == s3));
    }
}
/* output
s1 == s2: false
s1 == s3: true
*/
Copy after login

这里就很容易的了解 intern 实际上就是把普通的字符串对象也关联到常量池中。

The above is the detailed content of Comprehensive analysis of the contents of the Java String class (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template