Effective Java English Second Edition reading notes Item 5:avoid creating unnecessary objects.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.