Welcome to “Algorithms and the Beauty of Programming” ↑ pay attention to us!

String implementation method simple introduction:

public final class String

    implements java.io.Serializable, Comparable<String>, CharSequence { }

Three interfaces:

Java.io.Serializable: Serializable class is implemented by the java.io.Serializable interface. Any state of a class interface that does not implement this functionality is not serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and is used only to identify serializable semantics.

To allow serialization of subtypes of non-serializable classes, the subtypes may be responsible for saving and restoring the public, protected, and (if accessible) status package fields of superType. A subtype can only assume this responsibility if the class it extends has an accessible no-arg constructor that initializes the state of the class. Declare the category to be an error if it is not, serializable. The runtime will detect an error at the following locations.

During deserialization, the fields of the non-serializable class are initialized using the public or protected no-arg constructor, which subclasses must have access to serializable. The fields of the serializable subclass are recovered from the stream.

When iterating over a graph, you may encounter objects that do not support a serializable interface. In this case notSerializabeException is thrown and identifies the class’s non-serializable object.

Comparable: Compares this object in order with the specified objects. Returns a negative integer, zero, or positive integer because this object is less than, equal to, or greater than the specified object

CharSequence: Returns the length of this character sequence, which is a number.

—————————————————————————————————

Properties:

 private final char value[];

This is an array of characters of final type. It is used to store the contents of a String. As we can see from the fianl keyword, the contents of a String cannot be changed once initialized. Although there is an example: String s = “a”; S = “b” however, this is not a modification of s, but a repointer to a new String, from which we know that String is implemented using char[].

private int hash;

Cache string hash Code, default value 0;

private static final long serialVersionUID = -6849794470754667710L;

Use serial versionUID in JDK 1. 0. 2 for interoperability;

Since String implements the Serializable interface, it supports serialization and deserialization. Java’s serialization mechanism verifies version consistency by determining the serialVersionUID of a class at run time. During deserialization, the JVM compares the serialVersionUID in the incoming byte stream with the serialVersionUID of the corresponding local entity (class). If they are the same, they are considered the same and deserialization can be performed. Otherwise, an InvalidCastException occurs with an inconsistent serialization version.

private static final ObjectStreamField[] serialPersistentFields =

        new ObjectStreamField[0];

A class string is a special case in the serialized stream protocol. ObjectStreamField[] : array of ObjectStreamFields used to declare the serializable fields of a class.

—————————————————————————————————

Construction method:

1. Construct a String from an array of characters and a String

Arrays.copyof and arrays.copyofrange methods are used when creating strings from Arrays. These two methods copy the contents of the original character array into the String character array one by one.

public String(char value[], int offset, int count) {

        if (offset < 0) {

            throw new StringIndexOutOfBoundsException(offset);

        }

        if (count <= 0) {

            if (count < 0) {

                throw new StringIndexOutOfBoundsException(count);

            }

            if (offset <= value.length) {

                this.value = “”.value;

                return;

            }

        }

        // Note: offset or count might be near -1>>>1.

        if (offset > value.length – count) {

            throw new StringIndexOutOfBoundsException(offset + count);

        }

        this.value = Arrays.copyOfRange(value, offset, offset+count);

    }

2. Construct a String from a byte array

In Java, a String instance holds an array of char[] characters, which are stored in Unicode codes, strings and char in memory form, and byte in serialized form for network transmission or storage. So in many transfers and storage operations, you need to convert the byte[] array to the String. So, String provides a series of overloaded constructors to convert an array of characters into a String, and when it comes to converting between byte[] and String, you have to worry about encoding. String(byte[] bytes, Charset Charset) is used to decode the specified byte array into a Unicode char[] array, enough to create a new String.

3. Construct a String using StringBuffer and StringBuider

public String(StringBuffer buffer) {

        synchronized(buffer) {

            this.value = Arrays.copyOf(buffer.getValue(), buffer.length());

        }

    }

    public String(StringBuilder builder) {

        this.value = Arrays.copyOf(builder.getValue(), builder.length());

    }

So if you have a StringBuffer or a StringBuilfer object you can just use their toString method to get a String.

A private constructor

String provides a private constructor as well as a number of public constructors for programmers to use

String(char[] value, boolean share) {

    // assert share : “unshared not supported”;

    this.value = value;

}

This method differs somewhat from String(char[] value)

—————————————————————————————————

In the method is now also used in many methods:

Length () returns the length of the string

IsEmpty () returns whether the string isEmpty

CharAt (int index) returns the first character in the string

Char [] toCharArray() converts to an array of characters

Trim () remove all Spaces

ToUpperCase () is converted toUpperCase

ToLowerCase () is converted toLowerCase

String concat(String STR) Concates a String

String replace(char oldChar, char newChar) replace(oldChar, char newChar) with newChar.

Boolean matches(String regex) Checks whether the String matches the given regex regular expression

Boolean Contains (CharSequence s) Determines whether the string contains the character sequence S

String[] split(String regex, int limit) Split the String into limit portions according to the character regex.

 String[] split(String regex)

—————————————————————————————————

A brief description of the functions of several methods:

hashCode

The implementation of hashCode uses a mathematical formula:

s[0]*31^(n-1) + s[1]*31^(n-2) + … + s[n-1]

ReplaceFirst, replaceAll, and replace are different

String replaceFirst(String regex, String replacement)

String replaceAll(String regex, String replacement)

String replace(CharSequence target, CharSequence replacement)

(1) The replace parameter is char and CharSequence, that is, it can support the replacement of characters and strings (2)replaceAll and replaceFirst take regex, regular expression based substitutions. For example, replaceAll(” \d “, “*”) can replaceAll numeric characters in a string with asterisks; The same is all replacement, that is, replace a character or string in the source string with the specified character or string. If you want to replace only the first occurrence, you can use replaceFirst(), which is also based on regular expressions, but unlike replaceAll(), only replaces the first occurrence of the string; In addition, if the arguments used by replaceAll() and replaceFirst() are not based on regular expressions, they have the same effect as replace(), which also supports string operations;

Intern () method

public native String intern();

This method returns an internalized reference to a string object. The String class maintains an object pool of initially empty strings. When the intern method is called, it returns the instance of the pool if the pool already contains an equal String object, otherwise it adds a String to the pool and returns a reference to the String.

To continue, welcome to continue to pay attention to this public number, learn more about different programming thinking.