国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java javaTutorial Java String source code analysis

Java String source code analysis

Feb 27, 2017 pm 03:25 PM

Java String source code analysis

What is an immutable object?

As we all know, in Java, the String class is immutable. So what exactly are immutable objects? You can think of it this way: If an object cannot change its state after it is created, then the object is immutable. The state cannot be changed, which means that the member variables within the object cannot be changed, including the values ??of basic data types. Variables of reference types cannot point to other objects, and the state of objects pointed to by reference types cannot be changed.

Distinguish between objects and object references

For Java beginners, there are always doubts about String being an immutable object. Look at the following code:

String s = "ABCabc"; 
System.out.println("s = " + s); 
 
s = "123456"; 
System.out.println("s = " + s);

The printed result is:

s = ABCabc
s = 123456

First create a String Object s, then let the value of s be "ABCabc", and then let the value of s be "123456". It can be seen from the printed results that the value of s has indeed changed. So why do you still say that String objects are immutable? In fact, there is a misunderstanding here: s is just a reference to a String object, not the object itself. The object is a memory area in the memory. The more member variables, the larger the space this memory area occupies. A reference is just a 4-byte data that stores the address of the object it points to. The object can be accessed through this address.

In other words, s is just a reference, which points to a specific object. When s="123456"; after this code is executed, a new object "123456" is created, and the reference s re-points to the heart object, and the original object "ABCabc" still exists in the memory and has not changed. The memory structure is shown in the figure below:

Java String源碼分析

One difference between Java and C++ is that it is impossible to directly operate the object itself in Java. All objects They are all pointed to by a reference, and this reference must be used to access the object itself, including obtaining the value of member variables, changing the member variables of the object, calling the object's methods, etc. In C++, there are three things: references, objects and pointers, all three of which can access objects. In fact, references in Java and pointers in C++ are conceptually similar. They are the address values ??of stored objects in memory. However, in Java, references lose some flexibility. For example, references in Java cannot be used like Addition and subtraction are performed like pointers in C++.

Why are String objects immutable?

To understand the immutability of String, first take a look at the member variables in the String class. In JDK1.6, the member variables of String have the following:

public final class String 
  implements java.io.Serializable, Comparable<String>, CharSequence 
{ 
  /** The value is used for character storage. */ 
  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. */ 
  private final int count; 
 
  /** Cache the hash code for the string */ 
  private int hash; // Default to 0

In JDK1.7, the String class has made some changes, mainly changes The behavior of the substring method when executed is not related to the topic of this article. There are only two main member variables of the String class in JDK1.7:

public final class String 
  implements java.io.Serializable, Comparable<String>, CharSequence { 
  /** The value is used for character storage. */ 
  private final char value[]; 
 
  /** Cache the hash code for the string */ 
  private int hash; // Default to 0

As can be seen from the above code, the String class in Java actually It is an encapsulation of a character array. In JDK6, value is an array encapsulated by String, offset is the starting position of String in the value array, and count is the number of characters occupied by String. In JDK7, there is only one value variable, that is, all characters in value belong to the String object. This change does not affect the discussion of this article. In addition, there is a hash member variable, which is a cache of the hash value of the String object. This member variable is also irrelevant to the discussion of this article. In Java, arrays are also objects (please refer to my previous article Characteristics of Arrays in Java). So value is just a reference, which points to a real array object. In fact, after executing the code String s = "ABCabc";, the real memory layout should be like this:


Java String源碼分析

# The three variables #value, offset and count are all private, and no public methods such as setValue, setOffset and setCount are provided to modify these values, so String cannot be modified outside the String class. That is to say, once initialized, it cannot be modified, and these three members cannot be accessed outside the String class. In addition, the three variables value, offset and count are all final, which means that within the String class, once these three values ????are initialized, they cannot be changed. So the String object can be considered immutable.

So in String, there are obviously some methods, and calling them can get the changed value. These methods include substring, replace, replaceAll, toLowerCase, etc. For example, the following code:

String a = "ABCabc"; 
System.out.println("a = " + a); 
a = a.replace(&#39;A&#39;, &#39;a&#39;); 
System.out.println("a = " + a);

The printed result is:

a = ABCabc
a = aBCabc

那么a的值看似改變了,其實(shí)也是同樣的誤區(qū)。再次說明, a只是一個(gè)引用, 不是真正的字符串對(duì)象,在調(diào)用a.replace('A', 'a')時(shí), 方法內(nèi)部創(chuàng)建了一個(gè)新的String對(duì)象,并把這個(gè)心的對(duì)象重新賦給了引用a。String中replace方法的源碼可以說明問題:

Java String源碼分析

讀者可以自己查看其他方法,都是在方法內(nèi)部重新創(chuàng)建新的String對(duì)象,并且返回這個(gè)新的對(duì)象,原來的對(duì)象是不會(huì)被改變的。這也是為什么像replace, substring,toLowerCase等方法都存在返回值的原因。也是為什么像下面這樣調(diào)用不會(huì)改變對(duì)象的值:

String ss = "123456"; 
 
System.out.println("ss = " + ss); 
 
ss.replace(&#39;1&#39;, &#39;0&#39;); 
 
System.out.println("ss = " + ss);

打印結(jié)果:

ss = 123456
ss = 123456

String對(duì)象真的不可變嗎?

從上文可知String的成員變量是private final 的,也就是初始化之后不可改變。那么在這幾個(gè)成員中, value比較特殊,因?yàn)樗且粋€(gè)引用變量,而不是真正的對(duì)象。value是final修飾的,也就是說final不能再指向其他數(shù)組對(duì)象,那么我能改變value指向的數(shù)組嗎? 比如將數(shù)組中的某個(gè)位置上的字符變?yōu)橄聞澗€“_”。 至少在我們自己寫的普通代碼中不能夠做到,因?yàn)槲覀兏静荒軌蛟L問到這個(gè)value引用,更不能通過這個(gè)引用去修改數(shù)組。

那么用什么方式可以訪問私有成員呢? 沒錯(cuò),用反射, 可以反射出String對(duì)象中的value屬性, 進(jìn)而改變通過獲得的value引用改變數(shù)組的結(jié)構(gòu)。下面是實(shí)例代碼:

public static void testReflection() throws Exception { 
   
  //創(chuàng)建字符串"Hello World", 并賦給引用s 
  String s = "Hello World";  
   
  System.out.println("s = " + s); //Hello World 
   
  //獲取String類中的value字段 
  Field valueFieldOfString = String.class.getDeclaredField("value"); 
   
  //改變value屬性的訪問權(quán)限 
  valueFieldOfString.setAccessible(true); 
   
  //獲取s對(duì)象上的value屬性的值 
  char[] value = (char[]) valueFieldOfString.get(s); 
   
  //改變value所引用的數(shù)組中的第5個(gè)字符 
  value[5] = &#39;_&#39;; 
   
  System.out.println("s = " + s); //Hello_World 
}

打印結(jié)果為:

s = Hello World
s = Hello_World

在這個(gè)過程中,s始終引用的同一個(gè)String對(duì)象,但是再反射前后,這個(gè)String對(duì)象發(fā)生了變化, 也就是說,通過反射是可以修改所謂的“不可變”對(duì)象的。但是一般我們不這么做。這個(gè)反射的實(shí)例還可以說明一個(gè)問題:如果一個(gè)對(duì)象,他組合的其他對(duì)象的狀態(tài)是可以改變的,那么這個(gè)對(duì)象很可能不是不可變對(duì)象。例如一個(gè)Car對(duì)象,它組合了一個(gè)Wheel對(duì)象,雖然這個(gè)Wheel對(duì)象聲明成了private final 的,但是這個(gè)Wheel對(duì)象內(nèi)部的狀態(tài)可以改變, 那么就不能很好的保證Car對(duì)象不可變。

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

更多Java String源碼分析相關(guān)文章請(qǐng)關(guān)注PHP中文網(wǎng)!


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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Difference between HashMap and Hashtable? Difference between HashMap and Hashtable? Jun 24, 2025 pm 09:41 PM

The difference between HashMap and Hashtable is mainly reflected in thread safety, null value support and performance. 1. In terms of thread safety, Hashtable is thread-safe, and its methods are mostly synchronous methods, while HashMap does not perform synchronization processing, which is not thread-safe; 2. In terms of null value support, HashMap allows one null key and multiple null values, while Hashtable does not allow null keys or values, otherwise a NullPointerException will be thrown; 3. In terms of performance, HashMap is more efficient because there is no synchronization mechanism, and Hashtable has a low locking performance for each operation. It is recommended to use ConcurrentHashMap instead.

What are static methods in interfaces? What are static methods in interfaces? Jun 24, 2025 pm 10:57 PM

StaticmethodsininterfaceswereintroducedinJava8toallowutilityfunctionswithintheinterfaceitself.BeforeJava8,suchfunctionsrequiredseparatehelperclasses,leadingtodisorganizedcode.Now,staticmethodsprovidethreekeybenefits:1)theyenableutilitymethodsdirectly

How does JIT compiler optimize code? How does JIT compiler optimize code? Jun 24, 2025 pm 10:45 PM

The JIT compiler optimizes code through four methods: method inline, hot spot detection and compilation, type speculation and devirtualization, and redundant operation elimination. 1. Method inline reduces call overhead and inserts frequently called small methods directly into the call; 2. Hot spot detection and high-frequency code execution and centrally optimize it to save resources; 3. Type speculation collects runtime type information to achieve devirtualization calls, improving efficiency; 4. Redundant operations eliminate useless calculations and inspections based on operational data deletion, enhancing performance.

What is an instance initializer block? What is an instance initializer block? Jun 25, 2025 pm 12:21 PM

Instance initialization blocks are used in Java to run initialization logic when creating objects, which are executed before the constructor. It is suitable for scenarios where multiple constructors share initialization code, complex field initialization, or anonymous class initialization scenarios. Unlike static initialization blocks, it is executed every time it is instantiated, while static initialization blocks only run once when the class is loaded.

What is the Factory pattern? What is the Factory pattern? Jun 24, 2025 pm 11:29 PM

Factory mode is used to encapsulate object creation logic, making the code more flexible, easy to maintain, and loosely coupled. The core answer is: by centrally managing object creation logic, hiding implementation details, and supporting the creation of multiple related objects. The specific description is as follows: the factory mode handes object creation to a special factory class or method for processing, avoiding the use of newClass() directly; it is suitable for scenarios where multiple types of related objects are created, creation logic may change, and implementation details need to be hidden; for example, in the payment processor, Stripe, PayPal and other instances are created through factories; its implementation includes the object returned by the factory class based on input parameters, and all objects realize a common interface; common variants include simple factories, factory methods and abstract factories, which are suitable for different complexities.

What is type casting? What is type casting? Jun 24, 2025 pm 11:09 PM

There are two types of conversion: implicit and explicit. 1. Implicit conversion occurs automatically, such as converting int to double; 2. Explicit conversion requires manual operation, such as using (int)myDouble. A case where type conversion is required includes processing user input, mathematical operations, or passing different types of values ??between functions. Issues that need to be noted are: turning floating-point numbers into integers will truncate the fractional part, turning large types into small types may lead to data loss, and some languages ??do not allow direct conversion of specific types. A proper understanding of language conversion rules helps avoid errors.

What is the `final` keyword for variables? What is the `final` keyword for variables? Jun 24, 2025 pm 07:29 PM

InJava,thefinalkeywordpreventsavariable’svaluefrombeingchangedafterassignment,butitsbehaviordiffersforprimitivesandobjectreferences.Forprimitivevariables,finalmakesthevalueconstant,asinfinalintMAX_SPEED=100;wherereassignmentcausesanerror.Forobjectref

Why do we need wrapper classes? Why do we need wrapper classes? Jun 28, 2025 am 01:01 AM

Java uses wrapper classes because basic data types cannot directly participate in object-oriented operations, and object forms are often required in actual needs; 1. Collection classes can only store objects, such as Lists use automatic boxing to store numerical values; 2. Generics do not support basic types, and packaging classes must be used as type parameters; 3. Packaging classes can represent null values ??to distinguish unset or missing data; 4. Packaging classes provide practical methods such as string conversion to facilitate data parsing and processing, so in scenarios where these characteristics are needed, packaging classes are indispensable.

See all articles