Why is the string class designed to be final in Java?

Source: Internet
Author: User
Tags string methods

Great God Link: Why is the string class designed to be final in Java? -Programmer-Know

I made a re-typesetting and replaced one of those examples to get a better understanding.

String is a lot of practical features, such as "immutability", is an engineer's carefully designed artwork! Art is fragile! Final is to refuse inheritance, to prevent the world from the bear children to destroy, to maintain world peace!

1. What is immutable?

The string immutable is simple, for example, to give an existing string "ABCD" a second assignment to "Abcedl", not to modify the data at the original memory address, but to point back to a new object, the new address.

2. Why is string not mutable?

Open the JDK source code,java.lang.String class starting the first three lines, is written like this:

[Java]View PlainCopy
    1. public final  class string implements java.io.serializable,  comparable<string>, charsequence {  
    2.      /** string essence is a char array .  and is decorated with the final keyword. */  
    3.     private final  char value[];  
    4.      ...  
    5. &NBSP;&NBSP;&NBSP;&NBSP;...&NBSP;&NBSP;
    6. }  

First, the string class is decorated with the final keyword, which means that the string is not inheritable. See below, the main member field of the string class value is a char[] array, and is final decorated. Final-modified fields cannot be changed after they are created.

Some people think that this is the end of the story, in fact, No. Because although value is immutable, it is only the reference address of value that is immutable. The fact that array arrays are mutable is not blocked. The data structure of the array looks

This means that the array variable is just a reference on the stack, and the structure of the array is in the heap. The value in the string class is final decorated, except that the reference address of the stack called value is immutable. Not that the array itself is immutable in the heap. Look at the following example,

[Java]View PlainCopy
    1. Final int[] value={1,2,3}
    2. Int[] another={4,5,6};
    3. Value=another; //Compiler Error, final immutable

Value is final decorated, and the compiler does not allow me to point value to another address in the heap area. But if I do it directly on the array elements, it's done in minutes.

[Java]View PlainCopy
    1. Final int[] value={1,2,3};
    2. value[2]=100; //This time the array is already {1,2,100}

Or a more brutal reflex can be changed directly.

[Java]View PlainCopy
    1. Final int[] array={1,2,3};
    2. Array.set (Array,2,100); //array is also changed to {1,2,100}

So the string is immutable, and the key is because Sun's engineers, in all the string methods behind it, are careful not to move the elements in the array, without exposing the internal member fields.

Private final char value[] in this sentence, the function of privately owned access is greater than final. And the designer was careful to set the entire string to final prohibition inheritance, to avoid being destroyed by others. So the string is immutable and the key is at the bottom of the implementation, not a final. The test is that engineers construct data types and encapsulate the skill of the data.

3. What are the benefits of immutable?

The simplest reason for this is to be safe .

Example 1 [Java]View PlainCopy
  1. Package _12_01 string;
  2. Public Class Why string is designed to be immutable class you {
  3. public static void Main (string[] args) {
  4. String A, B, C;
  5. A = "test";
  6. b = A;
  7. c = b;
  8. String Processa = Processa (a);
  9. String PROCESSB = PROCESSB (b);
  10. String PROCESSC = PROCESSC (c);
  11. System.out.println (Processa);
  12. System.out.println (PROCESSB);
  13. System.out.println (PROCESSC);
  14. }
  15. static string Processa (String str) {
  16. return str + "A";
  17. }
  18. static string Processb (String str) {
  19. return str + "B";
  20. }
  21. static string Processc (String str) {
  22. return str + "C";
  23. }
  24. }
  25. OUTPUT
  26. TestA
  27. Testb
  28. Testc

When string supports non-variability, their values are well determined, regardless of which method is called.

If the string is mutable, it is possible to use StringBuffer to simulate a variable string, as in the following example.

[Java]View PlainCopy
  1. Package _12_01 string;
  2. Public Class Why string is designed to be immutable class 2 {
  3. public static void Main (string[] args) {
  4. StringBuffer A, B, C;
  5. A = new StringBuffer ("test");
  6. b = A;
  7. c = b;
  8. String Processa = Processa (a);
  9. String PROCESSB = PROCESSB (b);
  10. String PROCESSC = PROCESSC (c);
  11. System.out.println (Processa);
  12. System.out.println (PROCESSB);
  13. System.out.println (PROCESSC);
  14. }
  15. static String Processa (StringBuffer str) {
  16. return Str.append ("A"). ToString ();
  17. }
  18. static String processb (StringBuffer str) {
  19. return Str.append ("B"). ToString ();
  20. }
  21. static String processc (StringBuffer str) {
  22. return Str.append ("C"). ToString ();
  23. }
  24. }
  25. OUTPUT
  26. TestA
  27. Testab
  28. Testabc

Can see B=A,C=B, the programmer's intention is to hope that the variable is unchanged. Therefore, the security of string immutable is reflected here. In fact, the role of StringBuffer is to play the variable companion class role of String.

Example 2

Look at the following this HashSet use StringBuilder to do elements of the scene, the problem is more serious, and more covert.

[Java]View PlainCopy
  1. Class test{
  2. public static void Main (string[] args) {
  3. hashset<stringbuilder> hs=New hashset<stringbuilder> ();
  4. StringBuilder sb1=New StringBuilder ("AAA");
  5. StringBuilder sb2=New StringBuilder ("aaabbb");
  6. Hs.add (SB1);
  7. Hs.add (SB2); //This time HashSet is {"AAA", "AAABBB"}
  8. StringBuilder sb3=sb1;
  9. Sb3.append ("BBB"); //This time HashSet is {"aaabbb", "aaabbb"}
  10. SYSTEM.OUT.PRINTLN (HS);
  11. }
  12. }
  13. Output:
  14. [AAABBB, AAABBB]

The StringBuilder variables sb1 and SB2 respectively point to the literal "AAA" and "AAABBB" in the heap. Put them all into a hashset. There is no problem in this step. But if I later put the variable SB3 also point to the address of SB1, and then change the value of SB3, because StringBuilder has no immutability of protection, SB3 directly in the original "AAA" Address to change. The value that caused the SB1 also changed. At this time, there are two equal key values "AAABBB" on the HashSet. destroyed the the uniqueness of the HashSet key value . So do not use mutable types for HashMap and HashSet key values.

Non-denaturing support for thread safety

It is also known that in concurrent scenarios, multiple threads can read a resource at the same time without triggering a condition. Only writing to resources can be dangerous. Immutable objects cannot be written, so thread safety.

Immutability Support string constant pool

Finally, don't forget. String Another property of a string constant pool . as follows , the string one and two are assigned literal "something" values. They all point to the same memory address.

[Java]View PlainCopy
    1. String one = "somestring";
    2. String a = "somestring";


This saves memory space and improves efficiency in cases where strings are used in large numbers. But to achieve this feature, the immutability of string is the most basic necessary condition. If the contents of the string in the memory can be changed to change, it is completely meaningless to do so.

Transferred from: http://blog.csdn.net/u013905744/article/details/52414111

Why is the string class designed to be final in Java?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.