"Effective Java" reading notes

zhaozj2021-02-12  138

http://blog.9cbs.net/mingjava/archive/2004/06/26/27309.aspx

Http://blog.9cbs.net/mingjava/archive/2004/06/27/27880.aspx

http://blog.9cbs.net/mingjava/archive/2004/06/30/31070.aspx

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. Recommended methods are similar to inputStream is = null;

Try {is = /;} finally {is.close ();

Methods Common To All Objects

Item 7: When you override the Equals method, you must follow General Contact.

Be sure to double your way when you override Equals, in fact, the best way is not to overwrite this method. For example, in the following cases, you can not overwrite

1 Every instance of this class is unique, such as Thread class

2 If you don't care whether this class will provide a test logic equal approach

3 Ultra class has covered the equals method, and it is used by suitable subclasses

4 If this class is private or package-private, and you are confident that he will not be called

But when we want to distinguish between such a class, we must overwate this method. For example, the String class, a Date class, etc., we must follow the General Contact when it is overwritten, it is a contract. The main content of the contract is

1. x.equals (x) must return true

2. X.Equals (y) Returns true when you returns true when Y.Equals (x) returns TRUE

3. X.Equals (y) Returns True, y.Equals (z) Returns true, then x.equals (z) must return true

4. If there is no change, the return value of the X.Equals (y) should not change.

5. Non-empty objects x, x.equals (null) must return FALSE

Below is the author's suggestion how to properly override the equals method

1. Use == to check if the parameters are references to this object

2. Is it correct to determine the type of parameters with instanceof?

3. Convert parameters into appropriate types

4. Comparison class field is not a match

E.g:

Public Boolean Equals (Object O)

{

IF (o == this) return true;

IF (! (o instanceof xxxx) Return False;

XXX IN = (xxx) O;

Return ...... ..

}

In the end, it is important to pay attention to the way PUBLIC Boolean Equals (MyClass O), which is an overload that is not overridden Object's equals method Item 8: When you override Equals, you must overwrite the HashCode method.

This must be avoided, otherwise, when you are dealing with the Hash-Based collection, the error will appear. The key issue is to meet equal objects must have equal access. If you override the Equals method in the Phonenumber class, but there is no Hashcode method, then you will have problems when you do the following.

Map m = new hashmap ();

M.Put (New Phonenumber (408, 863, 3334), "Ming") When you call M.Get (New Phonenumber (408, 863, 3334)), you want to get ming but you get NULL, why is it because of the whole process? There are two examples of Phonenumber, one is a PUT is GET, but how can they get different havehcodes so that they can get the previously deposited MING.

Item 9: Always override the toString method

The form returned in Object's toString method is the type of Class, plus @ 加 16 16-based HashCode. Your best in your own class provides information on better expression instances, otherwise how others can understand.

Item 10: Be careful when covering the clone () method

If an object wants to be written, then to implement a clone () interface, this interface does not define any method, but if you don't implement this interface, CLONENOTSUPPPORTEDEXCEPTION will appear when the clone method is called, which is the author called Mixin interface type. Usually clone () method can be overwritten

Public Object Clone ()

{

Try {

Return super.clone ();

}

Catch (ClonenotsupportedException E) {}

}

But when you want a CLONE class with a modified reference field, you must copy the blueprints of the entire class. If you have modified the object you clone, you will affect the original instance, then this It is not necessary. So it should be like this clone ()

Public Object Clone () THROWS CLONENOTSUPPORTEDEXCEPTION

{

STACK RESULT = (stack) super.clone ();

Result.ersion (Object []) Elements.clone ();

Return Result;

}

Where Elements is the modified reference field in the Stack class. Note that if Elements is final, we will not be powerful, because you can't re-assapore it. In fact, if it is not a must, you don't have to use it.

Item 11: Cover the Comparable interface when considering appropriate

Thinking in java said more clearly, not much here.

More and more discovered this is a rare good book, Java programmers don't see this book is very regrettable. This chapter tells about classes and interface-related issues. These items are very important.

Item 12: minimizes the accessibility of classes and members

A good module design should be the most likely to encapsulate your internal information, which can minimize the degree of coupling between the modules. Developed in parallel, this will be accelerated, which will speed up the system to maintain. This issue is solved by accessing the control in Java.

Public means that this class is available in any range. Protected Indicates that only subclasses and classes can use private-package (default) to indicate that only private can be used in the package.

You should be as designed in 4321 when designing a class. If a class is just used by another class, you should consider designing it into the internal class of this class. Usually the class of public public should have a PUBLIC product, but we usually use a class to define all constants, which is allowed. However, it is necessary to ensure that these fields are either basic data type either to reference the pointing objects that cannot be modified. Otherwise they will mobilize. For example, in the definition below is unreasonable, there is no problem in the back. Public class con {public static final int [] data = {1, 2, 3}; // it is bag public static final string hello = "world"; public static final int i = 1;} Item 13: 不 不Class is more favored

Invoible class is meaning that they will not change, such as String classes. Their design is very convenient and high - they are threads. There are several rules for designing cannot modify classes:

Do not provide any way to modify the object to ensure that there is no way to be overwritten, you can design it to Final all fields to be designed as a Final All fields to make sure that the externally cannot access the modified components of the class cannot be modified. There is a disadvantage. Creating different objects when creating a different class, String is like this. Usually some solution is to provide a help class to make up, such as StringBuffer classes.

Item 14: The combination is more worth considering than inheritance

The most important way to realize code reusing is to inherit, but inherit is destroyed, causing the software's key mass. If the subclass inherits the parent class, it relies on the parent class from the method of inheriting from the parent class, once he changed the unpredictable result. The author introduces InstrumentHashSet as an alternative, the reason is that there is no understanding of the method of the parent class. The solution given by authors is to solve problems with packaging and forwarding methods by ginching instead of inheritance. Take the class that wants to extend as a private factory for this class. Pass the method parameters to this member variable and get the return value. The disadvantage of this is that such a class is not suitable for returning to the frame. Although inherited, we should not abuse, only we can determine that they are IS-A to have relationships.

Item 15: If you want to use inheritance, you must have quality assurance, otherwise don't use it.

In order to avoid the issuance of inheritance, you must provide accurate documentation to explain the problem that the relevant method may occur. Do not call the method that can be overwritten in the constructor, because the problem occurs when the subclass coverage method. Import java.util. *;

Public class subclass extends superclass {private final date; public subclass () {date = new date ();} public void m () {system.out.println (date);} public static void main (String [] args {Subclass S = new subclass (); sm ();}}

Class superclass {public superclass () {m ();} public void m () {}} Since the super () has been called before the Date is initialized, the first output NULL instead of the current time. Because of the functionality of the constructor when clone () or serialization, the readObject () and clone () methods are preferably not included in the method.

Item 16: Priority between interfaces and abstract classes

Interfaces and abstract classes are used to achieve polymorphism, but we should give priority to the interface. do you know? James said if he wants him to redesign Java, he will design all the interface. The advantage of an abstract class is to expand because it is inherited, and the method can be implemented within an abstract class, and the interface is not. Item 17: Interface should only be used to define types

The interface can be used for the Collection c = new xxxx (); this is our most common. Do not use interfaces to do other things, such as definitions of constants. You should define a class, which contains the Public Final Static field.

Item 18: Choosing the former between static and non-static internal classes

If a class is defined in other classes, it is a nested class, which can be divided into static internal classes, non-static internal classes, and anonymous classes. Static Member Class is the purpose of which is to serve Enclosing Class, if there are other purposes, you should design it into top-level classes. NonStatic Member Class is associated with Enclosing Class Instance, if you don't need to access Enclosing Class Instance, you should design it into static, or you will waste time and space. Anonymous Class is carried out simultaneously declared and initialization. Can be placed in any location of the code. Typical applications are Listener and Process Object such as Thread.

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

New Post(0)