Effective Java is a good book for Java learners. For target readers (who have a little programming foundation and development experience), she is concise and easy to understand. Each chapter is divided into several entries, which can be fully read and considered using the usual Fragmented time slice. I just read the second chapter, creating and destroying objects, and having no more basic knowledge from static factories, constructors, and so on, but I have a special feeling, it's just like seeing a girl who makes me feel at ease. The surprise is so wonderful, but it's also so shocking. It turns out that girls can still be so beautiful. The original books, so-called dizzy programming books, can be well written and directly hit the mind, so that people may feel at ease. As I wrote in my circle of friends, reading books is like tea, wine tasting, and life. She is completely different from think in 21-day proficient xxoo.
In Java is also unattainable to anyone (I read it with a deep bitterness ).
Let's talk too much about it. Let's start with the text.
More exciting, please follow: http://muscle1990.com /? P = 295
- Create and destroy objects
This chapter describes how to create and destroy objects, when and how to create, when, and how to destroy objects, and how to ensure that they can read and destroy objects in a timely manner ,, and how to manage various cleanup tasks that must be performed before object destruction.
- Article 1: static Factory
Let's take a look at this static factory method and return tired instances:
public static Boolean valueOf(boolean b){return b?Boolean.TRUE:Boolean.FALSE; }
By calling this method, you can easily use the factory to obtain an instance.
The static factory and constructor have the following advantages:
- They have names, as what you can see.
- You do not need to create a new object every time you call them.
- They can flexibly return any child type objects of the original type.
- When creating a parameterized instance, she makes the code more concise.
For example:
When we create a map using the constructor with parameters, we need:
Map<String,String> stringMap=new HashMap<String,String>();
However, suppose hashmap provides the following static factories:
public static <K,V> HashMap<K,V> newInstance(){return new HashMap<K,V>(); }
When creating a map, we can write it like this:
Map<String,String> stringMap =HashMap.newInstance();
Would you be pleasantly surprised if you often need to create objects at work?
- Article 2: when encountering multiple constructor parameters, consider using the constructor:
The static factory and constructor have a common limitation and cannot expand to a large number of optional attributes.
Consider a person's information, some are required, such as ID, name, and some are optional, such as area, height, weight, etc.
Method 1 with parameter Constructor
Package new_and_destory_object;/** @ author Mo shihao * moshihao@gmail.com muscle1990.com * @ version: 9:53:36 **/public class person {private string ID; // required private string name; // required private int height; // optional private int weight; // optional // Private xxx ooo; // optional // and so on... // optional public person (string ID, string name) {This. id = ID; this. name = Name;} public person (string ID, string name, int height) {This. id = ID; this. name = Name; this. height = height;} public person (string ID, string name, int height, int weight) {This. id = ID; this. name = Name; this. height = height; this. weight = weight;} public person (string ID, string name, int height, int weight, xxx Ooo ,...) {This. id = ID; this. name = Name; this. height = height; this. weight = weight ;...}}
However, when we create an object, it will look like this:
Person Muscle=new Person("helloworld","Muscle",172,55,........);
What if there are many attributes? In the actual project I participated in, I encountered more than 150 attributes. Do I need to write hundreds of parameters using the constructor's parameter setting method? And then select? Fill in data slowly? Save again? Oh my God!
Method 2: JavaBean setter Mode
Package new_and_destory_object;/** @ author Mo shihao * moshihao@gmail.com muscle1990.com * @ version: 9:53:36 **/public class person {private string ID; // required private string name; // required private int height; // optional private int weight; // optional // Private xxx ooo; // optional // and so on... // optional Public String GETID () {return ID;} public void setid (string ID) {This. id = ID;} Public String getname () {return name;} public void setname (string name) {This. name = Name;} public int getheight () {return height;} public void setheight (INT height) {This. height = height;} public int getweight () {return weight;} public void setweight (INT weight) {This. weight = weight ;}//...}
I believe that this method will not be unfamiliar to everyone. However, in the same situation, there are many attributes...
Person Muscle = new Person();Muscle.setId("helloworld");...
In addition, because the constructor is divided into several calls, the JavaBean may be inconsistent.
Method 3: builder Mode
Fortunately, there is also a third alternative, which can be as secure as the overlapping constructor and as easy to read and flexible as the JavaBean.
Package new_and_destory_object;/** @ author Mo shihao * moshihao@gmail.com muscle1990.com * @ version: 9:53:36 **/public class person {private string ID; // required private string name; // required private int height; // optional private int weight; // optional // and so on... public static class builder {// required attribute private final string ID; private final string name; // optional private int Height = 0; private int Weight = 0; // and so on... public Builder (string ID, string name) {This. id = ID; this. name = Name;} public builder height (INT height) {This. height = height; return this;} public builder weight (INT weight) {This. weight = weight; return this;} // and so on... public Person build () {return new person (this) ;}} public person (Builder) {id = builder. ID; name = builder. name; Height = builder. height; Weight = builder. weight ;}}
Note that person is unchangeable. Implementation of the following object creation:
Person Muscle = new Person.Builder("helloworld","Muscle").height(173).weight(55).build();
Such code is easy to write and easy to understand.
This part does not feel much for the time being. It is rarely used in a single case, but I have learned it.
- Article 4: The private constructor is used to enhance the non-instantiation capability.
This is a good story. I asked about it during the interview of HSBC gltc.
- Article 5: Avoid creating unnecessary objects
This part is particularly useful, not to mention:
String S = new string ("string"); // never write code like this. Please do it.
The value-assigned string is already an object instance. This means that an instance is added. If you perform frequent string operations, thousands of useless instances are generated.
String S = "string"; // This way, concise and clear, no waste
You also need to reuse reusable resources. Just like the example in the book, you can set the start time and End Time to static final, so that there is no need to instantiate each call.
Packing and unpacking problems:
Public static void main (string ARGs []) {// binning time required: 16 S // basic type time: 2 slong sum = 0l; For (long I = 0; I <integer. max_value; I ++) {sum + = 1;} system. out. println (SUM );}
If you do not know the difference between long and long, simply put, Long is the object, and long is the basic type. They need to be packed and unpacked for conversion. The efficiency is generally visible. The basic type is preferred. Do not slide and write the Error Type manually...
Remove expired Object Reference
Package new_and_destory_object; import Java. util. arrays; import Java. util. emptystackexception;/** @ author Mo shihao * moshihao@gmail.com muscle1990.com * @ version: 11:13:52 */public class Stack {public object [] elements; private int size = 0; private Static final int default_ininal_capacity = 16; Public stack () {elements = new object [default_ininal_capacity];} public void push (Object E) {ensurecapacity (); elements [size ++] = E;} public object POP () {If (0 = size) {Throw new emptystackexception ();} return elements [-- size];} private void ensurecapacity () {If (elements. length = size) {elements = arrays. copyof (elements, 2 * size + 1 );}}}
Because the stack will maintain the expired reference of the object, and understand JVM memory management, it should be clear that there are referenced objects, even if it knows it is garbage, it will not be recycled. Therefore, even if this code runs without any problems, it may cause the risk of memory overflow.
We need to modify the pop-up stack operation:
public Object pop(){if(0==size){ throw new EmptyStackException(); }Object result =elements[--size];elements[size] =null;return result;}
In general, as long as the class manages its own memory, we need to be cautious about memory leakage.
In addition, we also need to note that another common source of Memory leakage is cache. Once you put the object in the cache, it is easy to forget.
- Article 7: avoid using the termination method:
Honestly, I have never used it, but it's good to know about it.
Negative tive Java Reading Note (1) creating and destroying objects. It took about two hours for this reading note to carry a code. I haven't written such a reading note for a long time, shushan has a road. Come on!
Muscle Mo 2013.7.31. later written in the university dormitory