This immutable class to say do not understand, I was how to!

Author | silent king

Head Figure | CSDN downloaded from the Vision China

Brother, can you give me about why the String class is immutable right? 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!

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.

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 ()) , the always returns a new object, rather than the value before the impact.

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

Although call  substring ()  method cmower been taken, but the value is not changed cmower.

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


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.

 1public final class Writer {
 2    private final String name;
 3    private final int age;
 4
 5    public Writer(String name, int age) {
 6        this.name = name;
 7        this.age = age;
 8    }
 9
10    public int getAge() {
11        return age;
12    }
13
14    public String getName() {
15        return name;
16    }
17}

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:

 1public class Book {
 2    private String name;
 3    private int price;
 4
 5    public String getName() {
 6        return name;
 7    }
 8
 9    public void setName(String name) {
10        this.name = name;
11    }
12
13    public int getPrice() {
14        return price;
15    }
16
17    public void setPrice(int price) {
18        this.price = price;
19    }
20
21    @Override
22    public String toString() {
23        return "Book{" +
24                "name='" + name + '\'' +
25                ", price=" + price +
26                '}';
27    }
28}

2 fields, respectively. Price and the name, and the setter and getter, the rewritten toString () method. Then, a variable object field is added in the book Writer class.

 1public final class Writer {
 2    private final String name;
 3    private final int age;
 4    private final Book book;
 5
 6    public Writer(String name, int age, Book book) {
 7        this.name = name;
 8        this.age = age;
 9        this.book = book;
10    }
11
12    public int getAge() {
13        return age;
14    }
15
16    public String getName() {
17        return name;
18    }
19
20    public Book getBook() {
21        return book;
22    }
23}

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.

 1public class WriterDemo {
 2    public static void main(String[] args) {
 3        Book book = new Book();
 4        book.setName("Web全栈开发进阶之路");
 5        book.setPrice(79);
 6
 7        Writer writer = new Writer("沉默王二",18, book);
 8        System.out.println("定价:" + writer.getBook());
 9        writer.getBook().setPrice(59);
10        System.out.println("促销价:" + writer.getBook());
11    }
12}

The output results of the program are as follows:

1定价:Book{name='Web全栈开发进阶之路', price=79}
2促销价: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:

1public Book getBook() {
2    Book clone = new Book();
3    clone.setPrice(this.book.getPrice());
4    clone.setName(this.book.getName());
5    return clone;
6}

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.

1定价:Book{name='Web全栈开发进阶之路', price=79}
2促销价:Book{name='Web全栈开发进阶之路', price=79}

to sum up

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.

【End】

Recommended Reading 

GitHub open source project after another blocked provoke outrage, CEO personally apologize!

360 in response to security cloud disk appears unusual transactions; Apple's official website after another restriction iPhone; GitHub open source project shielded Microsoft engineers | Geeks headlines

2020 years, the five kinds of programming language will die

withstood million people live, recommended the United Nations since the end of the book fly migration path technology!

do not know what AWS that? This 11 key with you know AWS!

written contract Solidity of intelligent design patterns

You look at every point, I seriously as a favorite

Released 1864 original articles · won praise 40000 + · Views 16,920,000 +

Guess you like

Origin blog.csdn.net/csdnnews/article/details/105039893