It is often appropriate to reuse a single object instead of creating a new functionally equivalent object each time it is Needed. Reuse can both faster and more stylish. An object can always be reused if it is immutable.
String S=new string ("no"); DON "T do this!
The statement creates a new String instance each time it is executed.
String s= "yes";
This version uses a single String instance,avoid creating unnecessary objects.
Packagecreatobjects;ImportJava.util.Calendar;Importjava.util.Date;ImportJava.util.TimeZone; Public classPerson {Private FinalDate birthdate=NewDate (); //Other Fields,methods,and constructor omitted /** The starting and ending dates of the baby boom. */ Private Static FinalDate Boom_start; Private Static FinalDate Boom_end; //Condition:this class must be invoke,otherwise it would direct poor performance Static{Calendar gmtcal= Calendar.getinstance (Timezone.gettimezone ("GMT")); Gmtcal.set (1946, Calendar.january, 1, 0, 0, 0); //Set (int year, int month, int date, int hourofday, int minute, int//second)Boom_start =Gmtcal.gettime (); Gmtcal.set (1965, Calendar.january, 1, 0, 0, 0); Boom_end=Gmtcal.gettime (); } Public BooleanIsbabyboomer () {returnBirthdate.compareto (Boom_start) >= 0 && Birthdate.compareto (boom_end) < 0; }}
There ' s a new-to-create unnecessary objects in release 1.5.It was called Autoboxing,and It allows the programmer to mix Primitive and boxed primitive types,boxing and unboxing automatically as needed.
Prefer Primitives to boxed Primitives,and watch out for unintentional autoboxing.
Don ' t create a new object when you should reuse an existing one.
Don ' t reuse an existing object when you should create a new one.
Effective Java English Second Edition reading notes Item 5:avoid creating unnecessary objects.