Take you to understand an article about java String partial source code interpretation, let’s take a look with the editor
Member variables of String type
/** String的属性值 */ private final char value[]; /** The offset is the first index of the storage that is used. */ /**数组被使用的开始位置**/ private final int offset; /** The count is the number of characters in the String. */ /**String中元素的个数**/ private final int count; /** Cache the hash code for the string */ /**String类型的hash值**/ private int hash; // Default to 0 /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = -6849794470754667710L;
With the above member variables, you can know that the value of the String class is final and cannot be changed, so as long as a value changes, a new String type object will be generated, and the String data does not necessarily start from the 0th position of the array. element, but starts from the element pointed to by offset.
The following code generates a new object, and the final result is a new String value with a new value of "bbaa".
String a = new String("bb"); String b = new String("aa"); String c = a + b;
It can also be said that the length of String type objects is immutable. String splicing strings will generate a new object every time, so the efficiency of string splicing is definitely not as fast as the variable length StringBuffer and StringBuilder. .
However, in the following situation, two strings are quickly spliced:
String a = "aa" + "bb";
The reason is: Java has made a small optimization for its string splicing. It directly splices "aa" and "bb" are directly spliced into "aabb", and then the value is assigned to a. The String object only needs to be generated once, which saves two times of generating String compared to the above method, and is obviously much more efficient.
Let’s take a look at some of the common construction methods of String
1. Parameterless construction method:
public String() { this.offset = 0; this.count = 0; this.value = new char[0]; }
2. Pass in the constructor of a Sring type object
public String(String original) { int size = original.count; char[] originalValue = original.value; char[] v; if (originalValue.length > size) { // The array representing the String is bigger than the new // String itself. Perhaps this constructor is being called // in order to trim the baggage, so make a copy of the array. int off = original.offset; v = Arrays.copyOfRange(originalValue, off, off+size); } else { // The array representing the String is the same // size as the String, so no point in making a copy. v = originalValue; } this.offset = 0; this.count = size; this.value = v; }
3. Pass in the constructor of a character array
public String(char value[]) { int size = value.length; this.offset = 0; this.count = size; this.value = Arrays.copyOf(value, size); }
4. Pass in a string number and the starting element , Constructor of the number of elements
public String(char value[], int offset, int count) { if (offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if (count < 0) { throw new StringIndexOutOfBoundsException(count); } // Note: offset or count might be near -1>>>1. if (offset > value.length - count) { throw new StringIndexOutOfBoundsException(offset + count); } this.offset = 0; this.count = count; this.value = Arrays.copyOfRange(value, offset, offset+count); }
As can be seen from the above common constructors, when we generate a String object, we must assign values to the three attributes of the object: offset, count, and value. , so that we can get a completed String type.
Common functions:
1. Function to determine whether two strings are equal (Equal): In fact, it is to first determine whether the comparison instance is String type data, not Then return False, if they compare each character element to see if they are the same, if they are the same, return True, otherwise return False
public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = count; if (n == anotherString.count) { char v1[] = value; char v2[] = anotherString.value; int i = offset; int j = anotherString.offset; while (n-- != 0) { if (v1[i++] != v2[j++]) return false; } return true; } } return false; }
2. Function to compare the sizes of two strings (compareTo ): The input is two strings. The returned 0 means that the two strings have the same value. If the return is less than 0, the value of the first string is less than the value of the second string. If it is greater than 0, it means the first string. The value is greater than the value of the second string.
The comparison process is mainly as follows: starting from the first element of the two strings, the actual comparison is the ACII code of the two chars. If different values are added, the first different value will be returned. Difference, otherwise return 0
public int compareTo(String anotherString) { int len1 = count; int len2 = anotherString.count; int n = Math.min(len1, len2); char v1[] = value; char v2[] = anotherString.value; int i = offset; int j = anotherString.offset; if (i == j) { int k = i; int lim = n + i; while (k < lim) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) { return c1 - c2; } k++; } } else { while (n-- != 0) { char c1 = v1[i++]; char c2 = v2[j++]; if (c1 != c2) { return c1 - c2; } } } return len1 - len2; }
View Code
3. Determine whether a string starts with a prefix string, and tooffset is the same length
public boolean startsWith(String prefix, int toffset) { char ta[] = value; int to = offset + toffset; char pa[] = prefix.value; int po = prefix.offset; int pc = prefix.count; // Note: toffset might be near -1>>>1. if ((toffset < 0) || (toffset > count - pc)) { return false; } while (--pc >= 0) { if (ta[to++] != pa[po++]) { return false; } } return true; } public int hashCode() { int h = hash; if (h == 0) { int off = offset; char val[] = value; int len = count; for (int i = 0; i < len; i++) { h = 31*h + val[off++]; } hash = h; } return h; }
4. Connect two strings (concat)
public String concat(String str) { int otherLen = str.length(); if (otherLen == 0) { return this; } char buf[] = new char[count + otherLen]; getChars(0, count, buf, 0); str.getChars(0, otherLen, buf, count); return new String(0, count + otherLen, buf); }
Several ways to connect strings
1. The most direct, use + to connect directly
String a = new String("bb"); String b = new String("aa"); String c = a + b;
2. Use the concat (String) method
String a = new String("bb"); String b = new String("aa"); String d = a.concat(b);
3. Use StringBuilder
String a = new String("bb"); String b = new String("aa"); StringBuffer buffer = new StringBuffer().append(a).append(b);
It is used more often in the first and second methods, but the efficiency is relatively poor. The efficiency of using StringBuilder for splicing is higher.
[Related recommendations]
1. Is String an object or a class in java? Detailed explanation of String in java
2. Summary of the example tutorials of String class in Java
4. Share example tutorials of String class in Java
The above is the detailed content of Share some source code interpretation of java String. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function