This time again tell immutable, I how to

Brother, can you give me about why the String class is immutable (immutable) do? I want to study it and wonder why it can not be changed, such as a strong desire to want to study, like the vast sky. But the frustration limited their skill, and always feel that every layer of smoke and mirrors final. Your brother is always full of interesting articles, I would like to be able to understand that, I can certainly understand, can you write a write next?

After receiving the small private letter R readers, I always feel they have a responsibility incumbent upon one kind of non-immutable class should understand that, or I how to - you have the final say!

01, what is immutable class

If a class object is changed in a state no longer created by the constructor, then it is an immutable (the immutable) class. It all assignments completed only member variables in the constructor, it does not provide any setter methods for external classes to modify.

Remember the "evil" in the Maid of the tomb it? With that loud noise, the only channel was ruthlessly closed. Do contests the secret passages, I say that just to open your imagination, so you have a more intuitive impression of the immutable class.

Ever since the multi-threaded, productivity was infinitely magnified, all programmers love it, because powerful hardware capabilities are fully utilized. At the same time, all programmers it may feel fear, because accidentally, multithreading will bring state of the object becomes chaotic.

To protect the atomic state, visibility, orderly, programmers can say is that we do everything we can. Which, synchronized (synchronous) Keywords are the simplest and most entry of a solution.

If that class is immutable, then the object's state is immutable. In this case, each time you modify an object's state, will produce a new object for different threads, we programmers do not have to worry about concurrency problem.

02, a common immutable class

Mentioned immutable class, almost all programmers first thought is the String class. So why should String class is designed to be immutable it?

1) requires constant pool

String constant pool Java heap memory is a special storage area, when you create a String object, if this string does not exist in the constant pool, then create a; if already exists, it will not be created, and It is a direct reference to an object that already exists. Doing so can reduce the JVM memory overhead and improve efficiency.

2) hashCode needs

Because strings are immutable, so when it was created, it was cached hashCode, making it ideal as a hash value (for example, as HashMap of keys), multiple calls to only return the same value, to improve efficiency .

3) Thread Safety

As said before, as if the state of the object is variable, then in a multithreaded environment, it is likely to cause unpredictable results. And String are immutable, can be shared among multiple threads, no synchronization process.

So when we call any method of the String class (for example trim(), , substring()),toLowerCase() it always returns a new object, rather than the value before the impact.

String cmower = "沉默王二,一枚有趣的程序员";
cmower.substring(0,4);
System.out.println(cmower);// 沉默王二,一枚有趣的程序员
复制代码

While calling substring()method cmower was intercepted, but the value cmower not changed.

In addition String class, wrapper class Integer, Long, etc. are immutable class.

03, custom immutable class

Read an immutable class may be tempting, but you want to create a custom class immutable is probably a bit harder. But despite the difficulties that we, as a good programmer indispensable quality, is not easy because we can truly grasp it.

Next, please join me, from the definition of an immutable class bar. An immutable eh, must meet the following four conditions:

1) ensure that the class is final, it does not allow inherited by other classes.

2) ensure that all member variables (fields) that this is the case, they can only be initialized values ​​in the final configuration of the method, and will not be subsequently modified.

3) Do not provide any setter methods.

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

According to the above conditions, we define from 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() {
        return age;
    }

    public String getName() {
        return name;
    }
}
复制代码

Writer class is final, name and age is final, there is no setter method.

OK, this is said to share a lot of blog authors, readers widely loved, so a certain publishing house asked him to write a book (Book). Book class is defined as:

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

    public String getName() {
        return name;
    }

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

    public int getPrice() {
        return price;
    }

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

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}
复制代码

2 fields, respectively. Price and the name, the setter and getter and, after rewriting toString()method. Then, a variable object field is added in the book 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() {
        return age;
    }

    public String getName() {
        return name;
    }

    public Book getBook() {
        return book;
    }
}
复制代码

Book and added parameters, and Book getter method in the constructor method.

After completion of the above work, we have to create a new class of test to see if the state really Writer class immutable.

public class WriterDemo {
    public static void main(String[] args) {
        Book book = new Book();
        book.setName("Web全栈开发进阶之路");
        book.setPrice(79);

        Writer writer = new Writer("沉默王二",18, book);
        System.out.println("定价:" + writer.getBook());
        writer.getBook().setPrice(59);
        System.out.println("促销价:" + writer.getBook());
    }
}
复制代码

The output results of the program are as follows:

定价:Book{name='Web全栈开发进阶之路', price=79}
促销价:Book{name='Web全栈开发进阶之路', price=59}
复制代码

Oops, immutability Writer class is destroyed, the price has changed. To solve this problem, we need an additional piece of content to define rules immutable class:

If an immutable class contains an object variable of class, you will need to ensure that the return is a copy of a variable object. In other words, Writer class getBook()method should be amended as follows:

public Book getBook() {
    Book clone = new Book();
    clone.setPrice(this.book.getPrice());
    clone.setName(this.book.getName());
    return clone;
}
复制代码

In this case, Book after the object constructor initialization will not be modified. At this point, run WriterDemo, you will find price changes no longer occur.

定价:Book{name='Web全栈开发进阶之路', price=79}
促销价:Book{name='Web全栈开发进阶之路', price=79}
复制代码

04, summary

Immutable class has many advantages, such as, in particular, in a multi-threaded environment, it is very safe String class as mentioned earlier. Although each modification will create a new object, increasing the memory consumption, but this disadvantage compared to the advantages it brings, apparently trivial - nothing more than picking up a watermelon lost sesame.

Well, my dear readers, that's the entire content of the article, you can see here is the best programmers. The original is not easy, it must not white ticket, please point like it for this article , it will be my writing more quality articles strongest power.

If you think your article a little help, micro-channel search "  silence the king,  " the first time to read, respond to [ 666 ] [ 1024 ] more 500G HD instructional videos I carefully prepared for you (already categorized), as well as manufacturers of technology cattle surface finishing by a paper-source code has been included in the cloud, the portal ~

Guess you like

Origin juejin.im/post/5e7430386fb9a07c7d007fe2
Recommended