"Effective Java" reading notes

zhaozj2021-02-16  78

Finally opened this James, JAVA classic books, found that it is difficult to understand than a general English book. But it is very practical in Item, which is the Java programmer should understand.

Creating and destroying object

Item 1: Consider replacing the constructor, such as: public static boolean valueof (b? Boolean.true: boolean.false);} This benefit is that the method has a name, and it can be multiplexed. No new objects are generated in the constructor each call. Second it can also return a subclass of the return type. Whether there is no Public or Protected constructor, will not be inherited. There is also the name of the static factory method and other static methods names that are not easy to distinguish.

Item 2: Strengthen Singletom Property, for example: public class hello {private static final hello instance = new hell ();

PRIVATE HELLO () {} public static hello getinstance () {return instance

}} This private constructor can only be used inside to ensure single case mode! Item 3: Avoid creating duplicate objects to multiplexed non-modified objects as much as possible, so efficiency and performance will increase. For example, if the cycle is 100 String s = new string ("Hello") will create 100 object loops 100 String s = "Hello"; only one object is created. Very good reuse.

Item 4: Use private constructors to avoid being instantiated

For example, public utilityclass {private utilityclass () {}

///} Usually those tool classes are designed so

Item 5: Eliminate absolute object reference

Although GC is used in Java to manage memory, "memory leak" will be generated if not paying attention. For example, the following program public class stack {private object [] Elements; private int size = 0; public stack (int i) {this.Elements = new object [i];} public void push (Object E) {ENSURE (); Elements [Size ] = E;} public object pop () {i (size == 0) {} return elements [size--]; Because when he was played, it did not become a recyclable garbage object, and Stack maintained their absolute reference. Will not be changed. The improved method is the following way of writing public object pop () {if (size == 0) {} Object obj = Elements [- size]; Elements [size] = null; return obj;} But do not abuse NULL.

Item 6: Avoiding a Finalizer garbage collector is a low thread level running and cannot be forced to execute. The recommended method is similar to inputStream is = null; try or {is.close ();}

转载请注明原文地址:https://www.9cbs.com/read-19951.html

New Post(0)