From: http://blog.csdn.net/ilibaba/archive/2009/01/13/3769578.aspx
No. 7 comply with general conventions when rewriting the equals Method
In the following cases, you do not need to rewrite the equals method:
1. Different instances of the same class are essentially unique.
2. It does not matter whether the class provides the same logic function.
3. The parent class has changed the equals method. For the subclass, the inherited equals method is the most suitable.
4. A class is private or visible to the package, and its equals method is not called.
When you need to rewrite the equals method, follow the following conventions:
1. Inversion, that is, X. Equals (X) is true.
2. Symmetry, that is, if and only when X. Equals (Y) is true, Y. Equals (X) is also set to true.
3. Transmission, that is, for any X, Y, Z, if X. equals (Y) is true, and Y. equals (z) is also true, then X. equals (z) must also be true.
4. Consistency: For any X, Y, if X and Y are not modified, X. equals (y) either returns true consistently or false consistently.
5. For non-null references to X, X. Equals (null) must return false.
Suggestions for modifying the equals method:
1. Use the = Operator to check whether the real parameter is the same reference to the object.
2. Use instanceof to check whether the real parameters are of the correct type.
3. On the basis of 2, convert the real parameter to the correct type.
4. Check whether the Domain value of the real parameter is equal to that of the current object.
5. After the equals method is compiled, check whether the equivalence relationship is satisfied.
For example:
- Public Boolean equals (Object O)
- {
- If (O = This) return true;
- If (! (O instanceof XXXX) return false;
- XXX in = (XXX) O;
- Return ........
- }
Warning to rewrite the equals method:
1. Do not try to let the equals method do too much.
2. Do not make equals dependent on unreliable resources; otherwise, consistency will be violated.
3. Do not replace the objects in equals with other types.Note thatDo not provide the public Boolean equals (myclass O) method. overload is not the equals method of override object. The real parameter must be of the object type, but overload the equals method. It is acceptable if the two return the same result, but this method is not worth it.
Conclusion: Try not to look for trouble without rewriting the equals method. when you really need to rewrite the equals method, follow the general conventions because the object will be continuously transmitted in the program, therefore, the program may run abnormally, or even crash, and it is difficult to find the cause of the program crash. In short, follow the agreement!
No. 8 The hashcode method must be overwritten when the equals method is rewritten.
This must be avoided. Otherwise, an error will occur when you are dealing with the hash-based set. The key issue is that equal hashcode is required for equal objects. If you overwrite the equals method in the phonenumber class, but do not overwrite the hashcode method, the problem may occur when you perform the following operations.
- Map M = new hashmap ();
- M. Put (New phonenumber (408,863,333 4), "Ming ")
When you call m. when you get (New phonenumber (408,863,333 4), you want to get Ming but you get null. Why is there two phonenumber instances in the process, one is put and the other is get, but the two instances with the same logic get different hashcode. So how can we get the previously stored Ming.
No. 9 always needs to rewrite the tostring () method
The format returned by the tostring method of the object is the class type plus "@" and the hexadecimal hashcode, which is hard to understand. It is best to provide the tostring method in your class to better express the instance information. Otherwise, how can someone else understand it.
In practical applications, the tostring method should return all interesting information contained in the object. At the same time, it is best to provide a matched constructor or static factory method in the program, so that programmers can convert the object and its string representation back and forth.
When implementing the tostring method, you must determine whether to specify the format of the returned value in the document. The specified format can be used as a standard, unambiguous expression, but it also embeds the string representation into permanent data. If the expression is changed in the future, it will affect the system code and data. Whether or not you decide to specify the format, you should clearly express your intention in the document. Provides a programming access path for the information contained in the tostring returned value to obtain the information in the string returned by the tostring method. This avoids errors caused by the programmer's parsing of the string.
No. 10 rewrite clone with caution (for details about the clone method, see Java clone method)
To clone an object, implements cloneable interface is required to implement the clone () method.If you do not implement this interface, clonenotsupportedexception will occur when calling the clone method. This is the type of the interface called Mixin by the author. The clone () method can overwrite
- Public object clone ()
- {
- Try
- {
- Return super. Clone ();
- }
- Catch (clonenotsupportedexception E)
- {}
- }
However, when the class you want to clone contains modifiable reference fields, you must copy the entire class blueprint, if you modify the cloned object and the original Instance is affected, this is not desirable. So we should clone () like this ():
- Public object clone () throws clonenotsupportedexception
- {
- Stack result = (stack) Super. Clone ();
- Result. elements = (object []) elements. Clone ();
- Return result;
- }
Elements is a reference field that can be modified in the stack class. Note that if elements is final, we can't do anything, because we can't assign a new value to it. in fact, if it is not necessary, it is best not to use it.
Pay attention to the issues of deep replication and shallow replication. To implement deep replication, the class that implements the cloneable interface should first call Super. Clone, then correct any domain to be corrected, and copy any variable object of "deep structure.
If the clone method is improperly implemented, it will bring hidden bugs to the system, if you want to use similar functions, the best way is to provide some other methods (copy constructors or provide a static factory method to replace constructors) to replace object copying, or simply do not provide such capabilities.
Cloneable has many problems, so it is safe to say that other interfaces should not be extended (extend), and classes designed for inheritance should not be implemented (implement.
No. 11 consider implementing the comparable Interface
The compareto method is Java. lang. the only method in the comparable interface. It allows simple equal comparison and sequential comparison. If a class implements the comparable interface, it indicates that its instance has a built-in sorting relationship. All value classes in the Java platform library implement comparable. When the current object is compared with the specified object in sequence, a negative integer, 0, or a positive integer (<, =,>) is returned ).
The compareto method is subject to the following constraints: Self-inverse, symmetry, transmission, and non-null. When the compareto Method for numerical comparison is implemented, it also needs to prevent value overflow (for example, I is a large positive number and J is a large negative number, if I-j is used to determine the size, a negative number may be returned if the overflow occurs ).
Classes that violate the compareto conventions will also destroy other classes that depend on comparative relationships, including treeset, treemap, and tool classes collections and arrays. These classes contain search and sorting algorithms.
Compiling compareto is similar to equals, but there are several differences. Compareto does not need to check the type of the real parameter. If the type is not suitable, clsscastexception should be thrown. If it is null, nullpointerexception should be thrown. The domain itself is compared in sequence rather than equal comparison.
No. 12 minimizes the accessibility of classes and members
A good module design should encapsulate its internal information as much as possible. hidden information can minimize the coupling between modules. Parallel Development will undoubtedly speed up development and facilitate system maintenance. In Java, the access controller is used to solve this problem.
- Public indicates that this class is available in any range.
- Protected indicates that only classes in the subclass and package can be used.
- Default (private-package, that is, do not write) indicates that the package is available.
- Private indicates that only the class can be used
When designing, we should try our best to prevent every class or member from being accessed by the outside world. If a class is only used by another class, you should consider designing it as the internal class of this class. The access level of the subclass in the override superclass function cannot be lower than that in the superclass. A specific example is that when the interface methods are implemented, they must all be public, because the methods in the interface are all public.
Public classes should contain as few common domains as possible. classes that contain public variable domains are NOT thread-safe. This rule has an exception:It is allowed to expose class Constants by having a total of static final fields. The domain names are composed of uppercase letters separated by underscores.However, it must be ensured that these fields are either of the basic data type or that the referenced object cannot be modified. Otherwise they may be modified. For example, in the following definition, data is unreasonable. Others can change the content in the array and there is a security vulnerability. There are no problems in the next two:
- Public class con
- {
- Public static final int [] DATA = {1, 2, 3}; // It is bad
- Public static final string Hello = "world ";
- Public static final int I = 1;
- }
Note: The array with a non-zero length is always variable, soIt is almost always wrong to have a public static final array field.
There are two ways to solve this security risk:
① Replace the public method with a private array and a public non-Variable list
- Private Static final type [] private_values = {...};
- Public static final list values = collections. unmodifiablelis (arrays. aslist (private_values ));
② Replace the public array with a public method, which returns a copy of the private array. This method sacrifices a little performance.
- Private Static final type [] private_values = {...};
- Public static final type [] values (){
- Return (type []) private_values.clone ();
- }
In short, we should avoid turning any stray tired interfaces and members into part of the API. Except for the special circumstances of the public static final domain, the public class should not contain the public domain, make sure that the pair referenced by the static final domain is immutable.
No. 13 Non-variability
An instance of an immutable class cannot be modified. All information contained in each instance must be provided when the instance is created and remains unchanged throughout the lifetime of the object. For example, the string, biginteger, and bigdecimal classes are non-mutable classes. Reason: it is easier to design, implement, and use than variable classes, so it is not prone to errors and therefore secure.
To make a Class A non-mutable class, follow the following five rules:
① Do not provide any methods for modifying objects;
② There is no way to rewrite quilt categories;
③ Make all domains final;
④ Make all the domains private;
⑤ Ensure mutex access to any variable component. (If a class points to the domain of a mutable object, you must ensure that the customers of this class cannot live to point to the reference of these objects, and never use the object reference provided by the customer to initialize such a domain, do not return a reference to this object in any access method );
The above rules are a little more demanding than the real ones. In order to improve the performance, there are some ways to do this. For example, there is no way to make an external visible change to the object state, many non-mutable classes have one or more non-final redundant domains, caching an expensive computing result in these domains.
Non-mutable objects are essentially thread-safe, They do not require synchronization. Non-mutable objects can be freely shared. You can not only share mutable objects, but also share their internal information. Non-mutable objects provide a large number of components for other objects, whether they are mutable or immutable.
The only drawback of a non-variable class is that a separate object is required for each different value.String is like this. Generally, a solution is to provide a help class, such as the stringbuffer class.
There are three methods to make a class a mutable class:
① Declare a class as final;
② Make every method in this class final, rather than making the entire class final. The advantage of this method is that its subclass cannot be inherited, but new methods can be extended;
③ Declare the class constructor as private or package-level private, and add a static factory method to replace the public constructor. (although this method is not commonly used, but it is the most recommended)
If you choose to enable your non-mutable class to implement the serializable interface and contain one or more domains pointing to a mutable object, you must provide a display readobject or readresolve method. The default readobject method allows an attacker to create a variable instance from an immutable class.
In short, classes should be designed to be immutable unless there is a good reason. If a class cannot be made into a mutable class, you should try to limit its variability. The constructor should create a fully initialized object, and all the constraints should be established at this time. Instead of passing "only constructing some instances" to other methods, provides public initial methods beyond the constructor.
No. 14 combination takes precedence over inheritance
The most important way to implement code reuse is inheritance, but inheritance destroys encapsulation, resulting in insufficient software keys. If the subclass inherits the parent class, the method inherited from the parent class depends on the implementation of the parent class. Once it is changed, unpredictable results will occur. If the subclass and the superclass are in different packages and the superclass is not designed for expansion, inheritance will lead to the vulnerability. The author introduces the instrumentedhashset as an inverse example, because it does not understand the implementation of the parent class method. The solution provided by the author is to replace inheritance through combination, especially when an appropriate interface is used to implement a packaging class, the packaging class and the forwarding method are used to solve the problem. Use the class to be extended as a private final member variable of the class. Pass the method parameter to this member variable and obtain the return value. The disadvantage is that such a class is not suitable for the callback framework. Although inheritance is good, we should not abuse it. It is used only when we can determine the relationship between them is-.
No. 15 is either designed specifically for inheritance and provides document instructions, or prohibits inheritance.
It is very dangerous to inherit classes that are not described in the document, and its public methods may be changed. When designing a class specifically used for inheritance, you must pay attention to the following points (not applicable to final classes ):
① It is necessary to accurately describe the impact of rewriting each method, although such a description violates the document motto "A good API document should describe what a method has done, rather than how it is done ", but this is also caused by inheritance undermining program encapsulation.
② Constructor of classes that can be inherited must not call methods that can be rewritten, whether directly or indirectly. The superclass constructor runs before the constructor of the subclass. Therefore, the override method in the subclass is called before the constructor of the subclass runs. The following error occurs:
- Public class superclass {
- Private final date;
- Public superclass (){
- M ();
- }
- Public void M (){}
- }
- Final class sub extends superclass {
- Private final date;
- Public sub (){
- Date = new date ();
- }
- Public void M () {// overrides superclass. M, invoked by constructor superclass ()
- System. Out. println (date );
- }
- Public static void main (string [] ARGs ){
- Sub S = new sub ();
- S. M ();
- }
- }
In this program, null occurs during the first printing, because when m is called by the constructor superclass, sub has no chance to initialize the Date Field.
The same problem occurs in the methods similar to the constructor clone and readobject. Therefore, clone and readobject cannot call a method that can be rewritten, either directly or indirectly.
Implementation Method of "constructors must not call methods that can be rewritten": Move the code body of each method that can be rewritten to a private "auxiliary method, in addition, each method that can be rewritten calls its private auxiliary method, and then uses "directly calling a private auxiliary method that can be rewritten" to replace "each self-use call of the modifiable method ".
When designing classes for inheritance, cloneable and serializable interfaces are not recommended. The clone and readobject methods are similar in behavior to the constructor-"a method that can be rewritten cannot be called, either directly or indirectly." For the readobject method, the rewrite method in the subclass runs before the status of the subclass is deserialized. For the clone method, the rewrite method will run before the clone method of the subclass has the opportunity to modify the state of the cloned object. In either case, they will inevitably lead to program failure.
When serializable is implemented and the class contains readresolve or writereplace methods, you must make them protected instead of private, because private functions cannot be called by the quilt class.
For general classes that are neither final classes nor designed and written for subclass purposes, the best way to prevent problems is to disable subclass. There are two methods:
① Declare this class as final.
② Convert all constructors into private or package-level private, and add a public static factory method to replace the constructor.
Another alternative to inheritance is to use the packaging mode. For more information, see section 14 composite over inheritance.
The No. 16 interface is better than the abstract class
Differences between interfaces and abstract classes:
① The abstract class allows the implementation of some methods, but the interface is not allowed;
② To implement an abstract class, a class must be a subclass of the abstract class, and the class implementing the interface must define the required methods and comply with general conventions, no matter where the class is located;
An interface can construct a non-hierarchical result type framework. For example, an interface can inherit multiple other interfaces. You can also safely Add a class function.
Of course, you can also combine interfaces with abstract classes. For every important interface you want to export, first provide an abstract skeleton implementation class, the interface still serves to define the type, and the skeleton implementation class is responsible for all work related to the interface implementation.
Abstract classes also have obvious advantages. It can easily add a new method in a later version of a class, but it does not affect other related classes, and interfaces cannot do this.
In short, an interface is usually the best way to define multiple implementation types (except when the evolutionary accessibility is more important than flexibility and functionality, an abstract class should be used to define the type, however, you must understand the limitations of abstract classes and make sure they are acceptable ). If you have exported an important interface, you should also consider providing a skeleton implementation class. Finally, we should try our best to design some public interfaces with caution and conduct a comprehensive test on them by writing multiple implementations.
The No. 17 interface is only used to define the type.
An interface is only used to define a type. Do not use an interface to do other things (for example, defining constants in an interface. This constant interface mode is not applicable to interfaces ).
To export constants, you can use the following methods:
① If these constants are closely related to an existing class or interface, you can add them to this class or interface.
② Define a type-safe enumeration class and regard these constants as members of the enumeration type.
③ Use a tool class that can be instantiated (the constructor is set to private) to export these constants.