The Java Immutable Class (immutable) mechanism and the immutability of string

Source: Internet
Author: User

Immutable classes: When an instance of this class is created, the value of its member variable cannot be

Advantages:

1. The value of the thread-safe object cannot be changed, reducing the likelihood of concurrency errors

2. High efficiency when an object needs to be replicated, it only needs to copy the address of the object, without copying the native

Invariance, which guarantees the uniqueness of the hashcode, does not have to recalculate hashcode each time the cache is used, so the usual string as key

3. Easy to test and if the variables in the program are immutable, side effect is relatively small program as long as the written test once the basic no bug

Disadvantages:

Every change requires the creation of new objects that generate a lot of rubbish.

Design method:

Class adds a final modifier to ensure that the class is not inherited

Ensure all member variables private final

No setter available

When initializing variables, use deep copy

Public final class Immutabledemo {      private final int[] MyArray;      Public Immutabledemo (int[] array) {         //This.myarray = array;//Wrong             This.myarray = Array.clone ();    }  }

The Getter method returns to the image clone and does not return itself

String Object

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, which 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 ...    .    Public String (char value[]) {         this.value = arrays.copyof (value, value.length);//Deep copy Operation     }    ... Public     char[] ToCharArray () {     //cannot use arrays.copyof because of class initialization order issues        Cha R Result[] = new Char[value.length];        System.arraycopy (value, 0, result, 0, value.length);        return result;    }    ...}

Applies to constant pools

Thread Safety

class loader to use strings, immutable classes provide security for proper loading for example, if you want to load the Java.sql.Connection class, and this value is changed to myhacked.connection, it will cause an unknown damage to your database.

Suitable for HashMap

Note: string can change values by reflection mechanism

    Create the string "Hello World" and assign the reference s    string s = "Hello World";     System.out.println ("s =" + s); Hello World    //Get the Value field in String class field    valuefieldofstring = String.class.getDeclaredField ("value");    Change the access rights of the Value property    valuefieldofstring.setaccessible (true);    Gets the value of the ' value ' property on the S object    char[] value = (char[]) valuefieldofstring.get (s);    Change the 5th character in the array referenced by value    value[5] = ' _ ';    System.out.println ("s =" + s);  Hello_world

Results:

s = Hello Worlds = Hello_world

Reference:

Https://www.cnblogs.com/jaylon/p/5721571.html

Https://www.cnblogs.com/zhiheng/p/6653969.html

The Java Immutable Class (immutable) mechanism is invariant to 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.