[Valid Java] 3. Avoid creating unnecessary objects. Define tivejava
When you create an object, you do not need to initialize these variables every time you instantiate the object, you can use static and static blocks to fix the data of these variables.
Package cn. xf. cp. ch02.item5; import java. util. calendar; import java. util. date; import java. util. timeZone;/*** function: Generally, the method for creating an object * Time: 9:27:25 * file: PersonSlow. java * @ author Administrator **/public class PersonSlow {private final Date birthDate; public PersonSlow (Date birthDate) {this. birthDate = new Date (birthDate. getTime ();}/*** within a fixed time interval * @ return */public boolean isBetweenTheDate () {// obtain the start time of the Code Program under the corresponding GMT time standard, TimeZone. getTimeZone ("GMT") Calendar gmtCal = Calendar. getInstance (TimeZone. getTimeZone ("GMT"); // set the time to the corresponding position gmtCal. set (1946, Calendar. JANUARY, 1, 0, 0, 0); Date timeStart = gmtCal. getTime (); gmtCal. set (1965, Calendar. JANUARY, 1, 0, 0, 0); Date timeEnd = gmtCal. getTime (); return birthDate. compareTo (timeStart)> = 0 & birthDate. compareTo (timeEnd) <0 ;}}
Improve the above Code to the static code block mode.
Package cn. xf. cp. ch02.item5; import java. util. calendar; import java. util. date; import java. util. timeZone; public class PersonFast {private Date birthDate; // set the start time and End Time to private static final Date BOOM_START during class initialization; private static final Date BOOM_END; public PersonFast (Date birthDate) {this. birthDate = new Date (birthDate. getTime ();} // use a static code block to implement initialization with the class without changing static {Calendar gmtCal = Calendar. getInstance (TimeZone. getTimeZone ("GMT"); gmtCal. set (1946, Calendar. JANUARY, 1, 0, 0, 0); BOOM_START = gmtCal. getTime (); gmtCal. set (1965, Calendar. JANUARY, 1, 0, 0, 0); BOOM_END = gmtCal. getTime () ;}// compare the time function public boolean isBetweenDate () {return birthDate. compareTo (BOOM_START)> = 0 & birthDate. compareTo (BOOM_END) <0 ;}}
In this way, the private variables used to call the method are initialized at the beginning each time an object is created. If there are a large number of users calling this method, then the advantages of this method are shown.