Java.lang (String)

Source: Internet
Author: User

PublicFinalClass String implements Java.io.Serializable, Comparable<string>, charsequence {/** The value is used for Cha Racter storage. */PrivateFinal Char value[]; private int hash;    Default to 0 public String () {//no parameter constructor this.value = new Char[0];        The public string (string original) {this.value = Original.value;    This.hash = Original.hash; }/***** the constructor for passing in a character array, using the Arrays class in the Java.utils package to copy the ******/public String (char value[]) {this.value = arrays.copyof (VA    Lue, value.length); }/******* Pass in a string number, and start element, the 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.value = Arrays.copyofrange (value, offset, offset+count); }/********************* Similar method does not describe the **************************/public String (stringbuffer buffer) {synchronized (buffer) {this.value = arrays.copyof (Buffer.getvalue (), BUFFER.L        Ength ());        }} public Boolean equals (Object anobject) {if (this = = AnObject) {return true;            } if (AnObject instanceof string) {string anotherstring = (string) anobject;            int n = value.length;                if (n = = anotherString.value.length) {char v1[] = value;                Char v2[] = Anotherstring.value;                int i = 0;                    while (n--! = 0) {if (V1[i]! = V2[i]) return false;                i++;            } return true;    }} return false; }/***********s[0]*31^ (n-1) + s[1]*31^ (n-2) + ... + s[n-1]*********/public int hashcode () {int h = hash;/*** if H Ash is not computed, and the string is not empty, the hashcode is computed *****/if (h = = 0 && value.length > 0) {char val[] = value;            for (int i = 0; i < value.length; i++) {h = + * H + val[i];        } hash = h;    } return h;     }
The/***intern method is the native call, which is used to find the equivalent object in the constant pool in the method area through the Equals method, if it is not found in the constant pool
Opens a space to store a string and return a reference to the corresponding string, otherwise directly returns a reference to a string object already in the constant pool. /public Native String intern ();

Example:

String a = "abc"; String b = new String ("Ab1"). Intern (); if (a = = b) {  System.out.println ("a = = B");  } else {  System.out.printl N ("A is not equal to B");} Print out: a = = b
1. What is immutable class

The so-called immutable class, that is, after creating an instance of the class, the properties of the instance are immutable, and the wrapper classes and Java.lang.String classes provided by Java are immutable classes. When you create an instance of them, the properties of their instances are immutable.

It is important to note that for the following code

String s= "abc"; s= "Def";

You may be puzzled, not to say that string is immutable class, how can this change, usually I use the same. Note that S is the "ABC" reference to the string object, meaning that the reference is changeable and does not have anything to do with the property change of the object instance, please be aware of the distinction.

The 2.String class is designed to be an immutable cause
    1. The need for a string constant pool
    2. Allow string Object Cache Hashcode

      Hash codes for string objects in Java are used frequently, such as in containers such as HashMap.

      String invariance guarantees the uniqueness of the hash code, so you can cache it with confidence. This is also a performance optimization tool, meaning that you do not have to calculate a new hash code every time.

    3. Security: String is used by many Java classes (libraries) as parameters, such as the network connection address URL, file path, and the reflection mechanism required by the string parameter, if the string is not fixed, it will cause a variety of security risks.

    4. thread Safety: because strings are immutable, multithreading is secure, and the same string instance can be shared by multiple threads. This will not use synchronization because of thread-safety issues. The string itself is thread-safe.

3. How to implement an immutable class

Since non-mutable classes have so many advantages, we use the design of the string class to implement an immutable class.
The design of immutable classes usually follows several principles:

      1. Declares a class as final, so it cannot be inherited.
      2. Declare all members private so that you do not allow direct access to those members.
      3. Do not provide setter methods for variables.
      4. Declare all mutable members as final so that they can be assigned only once.
      5. Initializes all members through the constructor, making deep copy.
      6. In the getter method, do not directly return the object itself, but instead clone the object and return a copy of the object.

Java.lang (String)

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.