In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to create Java immutable objects, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
Foreword:
Why is String an immutable class (immutable object)? I want to study it, want to know why it is immutable, this strong desire is like want to study the vast starry sky. But their own skills are limited, always feel foggy to see the next layer. Second brother, your article is always interesting. I think I can make it clear and I can read it. Can I write it next?
Https://github.com/itwanger/toBeBetterJavaer
01. What is an immutable class
If the state of an object of a class is not changed after it is created by a constructor, it is an immutable class. All of its member variables are assigned only in the constructor, and no setter methods are provided for external classes to modify.
Do you still remember the tomb of the Dragon Girl in the Divine carving Heroes? With that loud noise, the only passageway was mercilessly closed. Don't take that secret tunnel seriously. I'm just saying this to open your imagination and give you a more intuitive impression of immutable classes.
Since the advent of multithreading, productivity has been infinitely magnified, and all programmers love it because powerful hardware capabilities are fully utilized. But at the same time, all programmers are afraid of it, because if not careful, multithreading will mess up the state of the object.
We programmers can be said to do their best to protect the atomicity, visibility and order of the state. Among them, the synchronized keyword is the simplest and most rudimentary solution.
If a class is immutable, then the state of the object is immutable. In this way, each time the state of an object is modified, a new object is created for different threads to use, and we programmers no longer have to worry about concurrency.
02. Common immutable classes
When it comes to immutable classes, the first thing almost all programmers think of is the String class. So why is the String class designed to be immutable?
1) need for constant pool
A string constant pool is a special storage area in Java heap memory. When you create a String object, if the string does not exist in the constant pool, create one; if it already exists, it will not be created again, but will directly reference the object that already exists. Doing so reduces the memory overhead of JVM and improves efficiency.
2) the need for hashCode
Because a string is immutable, its hashCode is cached when it is created, so it is ideal as a hash (such as a key for HashMap), and multiple calls return only the same value to improve efficiency.
3) Thread safety
As mentioned before, if the state of the object is variable, it is easy to cause unpredictable results in a multithreaded environment. On the other hand, String is immutable and can be shared among multiple threads without synchronous processing.
Therefore, when we call any method of the String class (such as trim (), substring (), toLowerCase ()), we always return a new object without affecting the previous value.
String cmower = "Silent King 2, an interesting programmer"; cmower.substring (0Magne4); System.out.println (cmower); / / Silent King 2, an interesting programmer
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 also immutable.
03. Hand masturbation is immutable
It may be easy to understand an immutable class, but it may be a little difficult to create a custom immutable class. But moving forward in the face of difficulties is an indispensable quality for us as good programmers, and it is precisely because it is not easy that we can really master it.
Next, please come with me to customize an immutable class. An immutable ah, the following four conditions must be met:
1) make sure that the class is final and is not allowed to be inherited by other classes.
2) make sure that all member variables (fields) are final so that they can only initialize values in the constructor and will not be modified later.
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 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 () {return age;} public String getName () {return name;}}
The Writer class is final, name and age are also final, and there are no setter methods.
OK, the author is said to share many blogs and is widely loved by readers, so so-and-so publishing house asked him to write a book (Book). The Book class is defined as follows:
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 +'}';}}
The two fields, name and price, and getter and setter, are the overridden 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 () {return age;} public String getName () {return name } public Book getBook () {return book;}}
The Book parameter and the getter method of Book are added to the construction method.
With all this done, let's create a new test class to see if the state of the Writer class is really immutable.
Public class WriterDemo {public static void main (String [] args) {Book book = new Book (); book.setName ("the way to advance the full stack development of 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 ("Promotion Price:" + writer.getBook ());}}
The result of the program output is as follows:
Pricing: Book {name='Web full stack development step forward', price=79}
Promotion price: Book {name='Web full stack development advanced road', price=59}
Too bad, the immutability of the Writer class has been destroyed and the price has changed. To solve this problem, we need to add a rule to the definition of immutable classes:
If an immutable class contains an object of a mutable class, you need to make sure that a copy of the mutable object is returned. That is, the getBook () method in the Writer class should be modified to:
Public Book getBook () {Book clone = new Book (); clone.setPrice (this.book.getPrice ()); clone.setName (this.book.getName ()); return clone;}
In this way, the Book object initialized by the constructor will not be modified. At this point, run WriterDemo and you will find that the price no longer changes.
Pricing: Book {name='Web full stack development step forward', price=79}
Promotion price: Book {name='Web full stack development advanced road', price=79}
04. Summary
Immutable classes have many advantages, just like the String class mentioned earlier, especially in a multithreaded environment, it is very safe. Although each modification creates a new object and increases memory consumption, this disadvantage is obviously negligible compared to its advantages-nothing more than picking up watermelons and losing sesame seeds.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.