Immutable classes in Java

Source: Internet
Author: User

This article is published in sync with the personal blog zhiheng.me, titled: Immutable Classes in Java.

Immutable classes in Java

Immutable class (Immutable Objects): When an instance of a class is created, its contents cannot be changed, i.e. its member variables cannot be modified.

Mutable class (Mutable Objects): Once an instance of a class is created, its contents can be modified.

The wrapper and String classes of the eight basic types in Java are non-mutable classes, while most other classes belong to mutable classes.

The same as the reference immutable difference

It is important to note that immutable classes cannot be changed because an instance of the class is immutable, not a reference to that instance.

String s = "abc"; System.out.println ("s:" + s);  Output S:abcs = "xyz"; System.out.println ("s:" + s);  Output s:xyz

The above code shows that the immutable class String seems to be able to change the value, but it is not. The variable s is simply a reference to an instance of the String class that stores the address of the instance object in memory. The "Change" in the third line of the code is actually a new instantiation of a String object, and the direction of S is modified to the new object, and the original object has not changed in memory, only a reference to it is missing, and it will remain unchanged until garbage collection in the future.

 Public classImmutable { Public Static voidMain (string[] args) {String str=NewString ("ABC"); String str2=str; System. out. println (str = = STR2);//trueSTR2 ="CBA"; System. out. println (str = = STR2);//falseSystem. out. println (str = = row (str));//trueSystem. out. println (str = = Other (str));//false    }     Static Privatestring Row (string s) {returns; }    Static Privatestring Other (string s) {s="XYZ";//Here the parameter S points to the new string object, and the referenced address is changed        returns; }}

So we see that for an immutable class, the object is changed by creating a new object and pointing the reference to the new object.

In general, fields initialized with the final modifier of the keyword are immutable, and immutable refers to immutable references. Specifically, the memory address of the object referred to by the reference is immutable, but not the object is immutable. If the object is also immutable, then the object is an instance of the immutable class.

public class Immutable {public     static void Main (string[] args) {        immutable immutable = new immutable ();        Final Inner Inner = Immutable.new Inner ();        Inner.value = 123; Instance variable        //The following statement compilation error, Inner is final and cannot be directed to a new object (change point to address)        //inner = it.new inner ();        Inner inner2 = Inner; Copied a reference, inner and Inner2 point to the same object        System.out.println (inner);//Will call the ToString method output object memory address        System.out.println ( INNER2); Inner and Inner2 have the same address        System.out.println (inner.value);//Output 123        System.out.println (inner2.value);// Output 123        inner2.value = 321;        SYSTEM.OUT.PRINTLN (inner); Output 321    }     class inner{        private int value;}    }
How immutable classes are implemented

The state of the immutable object cannot be changed after it has been created, and any change to it should result in a new object.

Therefore, the definition of an immutable class should have the following characteristics:

    1. All members are private final.
    2. Does not provide a way to change members, for example: setxxxx
    3. Make sure that all methods are not overloaded. There are two ways to do this: Use the final class (Strong immutable Class), or add all class methods to final (weakly immutable classes).
    4. If a class member is not a base type (primitive type) or an immutable class, you must ensure that the class is immutable by using a deep copy (that is, a new instance of the class rather than a reference) in the member initialization (in) or Getter method (out).
    5. If necessary, override the hashcode and Equals methods, and ensure that two objects that are judged equal by the Equals method should also be equal hashcode.

Here is an example:

Public final class Immutabledemo {      private final int[] MyArray;      Public Immutabledemo (int[] array) {    //This.myarray = array;//Error!    This.myarray = Array.clone ();//Correct  }    Public int[] Get () {    return Myarray.clone ();}  }

The wrong method in the previous example does not guarantee immutability, the MyArray and the parameter array point to the same memory address, and the user can change the value of the MyArray inside the instance by modifying the value of the array object outside of the Immutabledemo instance. The correct approach is to pass the value of the array to myArray through a deep copy. Similarly, the Getter method cannot directly return the object itself, but should be a clone of the object and return the copy of the object, which avoids the object leakage, prevents the internal variable member object through the getter to directly manipulate the member variables, resulting in the member variable changes.

For non-mutable classes, String is a typical example, and looking at its source code also helps us design immutable classes.

The advantages of immutable classes

The immutable class has two main bit, efficiency and safety.

    • Efficiency

      When an object is immutable, it is necessary to copy the contents of the object without duplicating its own address, and copying the address (usually a pointer size) requires only a small amount of memory and is highly efficient. Also, there is no effect on other variables that reference the object.

      In addition, immutability guarantees the uniqueness of the hashcode, so you can safely cache without having to recalculate the new hash code every time. Hash codes are used frequently, such as in containers such as HashMap. The hashcode cache can improve the performance of containers with immutable class instances as key.

    • Thread Safety

      In multithreaded situations, the value of a mutable object is likely to be changed by other processes, which can result in unpredictable results, while using immutable objects avoids the process of synchronizing locking and so on, so that immutable classes are thread-safe.

Of course, immutable classes also have drawbacks: every "change" of immutable classes produces new objects, so there is inevitably a lot of rubbish in use.

Immutable classes in Java

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.