Brother, can you tell me why String is immutable? My desire to study it, to know why it is immutable, is as strong as my desire to study the vastness of the starry sky. But helpless oneself skill is limited, feel from beginning to end look at flowers in fog lie between a layer. Second brother, your article is always full of interest. I think I can explain it clearly, and I can also read it clearly. Can YOU write it down next?

When I receive a private letter from my reader, I always feel duty-bound to tell immutable what it is to be, or else it is up to you!

What is an immutable class

Objects of a class are immutable if their state does not change after they are created by constructors. The assignment of all its member variables is done only in the constructor and does not provide any setter methods for external classes to modify.

Remember the tomb of xiaolongnu in The Return of the Condor Heroes? With that loud bang, the only passageway was ruthlessly closed. Don’t bother with the secret tunnel, I’m just saying this to open your imagination and give you a better picture of immutable classes.

Since the advent of multithreading, productivity has been infinitely amplified, and all programmers love it because the powerful hardware capabilities are fully utilized. But at the same time, all programmers are afraid of it, because if you’re not careful, multithreading can mess up the state of objects.

We programmers do everything we can to preserve atomicity, visibility, and order of states. The synchronized keyword is one of the simplest and most basic solutions.

If a class is immutable, then the state of an object is also immutable. This way, every time you change the state of an object, a new object is created for a different thread to use, and we programmers don’t have to worry about concurrency anymore.

02. Common immutable classes

When you think of immutable classes, the first thing that almost every programmer thinks of is the String class. So why is the String class designed to be immutable?

1) Constant pool needs

The String constant pool is a special storage area in the Java heap. When you create a String object, if the String does not exist in the constant pool, you create one. If the object already exists, it is not created, but refers directly to the existing object. Doing so reduces the MEMORY overhead of the JVM and improves efficiency.

2) Need for hashCode

Because a string is immutable, its hashCode is cached when it is created, making it ideal for a hash value (say, as a key of a HashMap) that returns the same value multiple times to improve efficiency.

3) Thread safety

As mentioned earlier, if the state of an object is mutable, then in a multi-threaded environment it is easy to have unexpected results. Strings, on the other hand, are immutable and can be shared between multiple threads without synchronization.

Therefore, when we call any method of the String class (trim(), SubString (), toLowerCase()), we always return a new object without affecting the previous value.

String cmower = "Silent King II, a funny programmer.";
cmower.substring(0.4);
System.out.println(cmower);// Silence King 2, an interesting programmer
Copy the code

Although the CMOwer is intercepted by calling the substring() method, the value of the CMOwer does not change.

In addition to the String class, the wrapper classes Integer, Long, and so on are immutable.

03. Custom immutable classes

While it may be easy to understand an immutable class, creating a custom immutable class may be a bit more difficult. But knowing what’s going on is an essential quality of being a good programmer, and because it’s not easy, we can really master it.

Next, please customize an immutable class with me. An immutable must meet the following four conditions:

1) Ensure that classes are final and cannot be inherited by other classes.

2) Make sure that all member variables (fields) are final, so that they can only be initialized in the constructor and will not be modified later.

3) Do not provide any setter methods.

4) If you want to change the state of the class, you must return a new object.

Based on the above conditions, we customize a simple immutable class Writer.

public final class Writer {
    private final String name;
    private final int age;

    public Writer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public int getAge(a) {
        return age;
    }

    public String getName(a) {
        returnname; }}Copy the code

The Writer class is final, name and age are final, and there are no setter methods.

OK, it is said that the author shared a lot of blogs and was widely loved by readers, so xx publishing House asked him to write a Book. The Book class is defined like this:

public class Book {
    private String name;
    private int price;

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice(a) {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    @Override
    public String toString(a) {
        return "Book{" +
                "name='" + name + '\' ' +
                ", price=" + price +
                '} '; }}Copy the code

Two fields, name and price, getter and setter, rewritten toString() method. Then, append a mutable object field, book, to the Writer class.

public final class Writer {
    private final String name;
    private final int age;
    private final Book book;

    public Writer(String name, int age, Book book) {
        this.name = name;
        this.age = age;
        this.book = book;
    }

    public int getAge(a) {
        return age;
    }

    public String getName(a) {
        return name;
    }

    public Book getBook(a) {
        returnbook; }}Copy the code

And appends the Book argument to the constructor, along with the getter method for Book.

With that done, let’s create a new test class to see if the state of the Writer class really is immutable.

public class WriterDemo {
    public static void main(String[] args) {
        Book book = new Book();
        book.setName("The Path to Full Stack Development on the Web");
        book.setPrice(79);

        Writer writer = new Writer("Silent King II.".18, book);
        System.out.println(Pricing: + writer.getBook());
        writer.getBook().setPrice(59);
        System.out.println("Promotional price:"+ writer.getBook()); }}Copy the code

The output of the program is as follows:

Pricing: Book {name ='The Path to Full Stack Development on the Web', price=79} Book{name='The Path to Full Stack Development on the Web', price=59}
Copy the code

Oops, the immutability of the Writer class is broken, and the price changes. To solve this problem, we need to append a rule to the definition of immutable classes:

If an immutable class contains objects of a mutable class, you need to ensure that a copy of the mutable object is returned. That is, the getBook() method in the Writer class should be changed to:

public Book getBook(a) {
    Book clone = new Book();
    clone.setPrice(this.book.getPrice());
    clone.setName(this.book.getName());
    return clone;
}
Copy the code

In this way, the Book object initialized by the constructor will not be modified. At this point, run WriterDemo and you’ll see that the price has stopped changing.

Pricing: Book {name ='The Path to Full Stack Development on the Web', price=79} Book{name='The Path to Full Stack Development on the Web', price=79}
Copy the code

04,

Immutable classes have many advantages, like the String class mentioned earlier, especially in multithreaded environments, where they are very secure. Although each change creates a new object and increases memory consumption, this disadvantage is obviously insignificant compared to the advantages it brings – it is nothing more than a penny for every penny.

Well, my dear readers, that’s all for this article, and the best programmers you can see here. Original is not easy, do not want a free ticket, please praise this article, it will be the strongest motivation for me to write more high-quality articles.

If you feel that the article is a little help to you, please wechat search “Silent King two” for the first time to read, reply [666] [1024] more I prepared for you 500G HD teaching video (has been classified), as well as dfactory technology niu people finishing the face by a copy, the source of this article has been included in the code cloud, portal ~