Effective Java creating and destroying objects

Source: Internet
Author: User
Tags sodium

Effective Java reads notes and refines the contents of the book in a way that suits its own understanding. "Effective Java" is a very useful book, reading methods should be quick to understand, summarize, and then apply. Rather than, a word one word to scrutinize, study. So, nerds are generally very xx, in my eyes.

Made in 2016.07.24

1, using static methods instead of constructors, here is a good example:

 Public Static Final New Boolean (true);  Public Static Final New Boolean (false);  Public Static Boolean ValueOf (boolean  b) {          return b?  Boolean.TRUE:Boolean.FALSE;}

In conjunction with the code, valueof is more meaningful than a constructor, and second, VALUEOF returns the final static member, which avoids the creation of unnecessary objects.

2, builder Builder. This is awesome, using the Java inner class.

 PackageCN.J; Public classnutritionfacts {Private Final intservingsize; Private Final intservings; Private Final intcalories; Private Final intfat; Private Final intsodium; Private Final intcarbonhydrate;  Public Static classBuilder {Private Final intservingsize; Private Final intservings; Private intCalories = 0; Private intFat = 0; Private intSodium = 0; Private intCarbonhydrate = 0;  PublicBuilder (intServingsize,intserving) {             This. servingsize =servingsize;  This. servings =serving; }                  PublicBuilder Calories (intval) {             This. Calories =Val; return  This; }                  PublicBuilder Fat (intval) {             This. Fat =Val; return  This; }                  PublicBuilder Carbonhyate (intval) {             This. carbonhydrate =Val; return  This; }                  PublicBuilder Sodium (intval) {             This. sodium =Val; return  This; }                  Publicnutritionfacts Build () {return NewNutritionfacts ( This); }    }         Privatenutritionfacts (Builder builder) {Servingsize=builder.servingsize; Servings=builder.servings; Calories=builder.calories; Fat=Builder.fat; Sodium=Builder.sodium; Carbonhydrate=builder.carbonhydrate; }          Public Static voidMain (string[] args) {nutritionfacts CocaCola=NewNutritionfacts.builder (240,80). Calories (+) sodium (+). Carbonhyate (27). build (); }}

In combination with the code, if you simply initialize those parameters with a constructor, it can be cumbersome, difficult to read, and error-prone to use.

For example, new Test (1,2,3,4,5,6,7,8,9);

In the form of the above code, nutritionfacts CocaCola = new Nutritionfacts.builder (240,80). Calories (+). Sodium (27). Build (), readability is very strong. The builder mode simulates a named optional parameter.

I vaguely remember that the project I was working on had seen the builder's writing.

3, through the private constructor to strengthen the ability of non-instancing, which is very very practical! Because the tool classes in the project are too common, the ability to harden non-instancing is required. The following code is my own Sonnblog code:

/*** @ClassName: Stringutil * @Description: String Processing Tool class *@authorNameless * @date 2016-4-30 pm 10:26:48 *@version1.0*/ Public Final classstringutill{PrivateStringutill () {} Public Static Booleanisstringempty (String str) {if(NULL= = Str| | "". Equals (str)) {            return true; }        return false; }         Public Static Booleanisthesamestr (String str1,string str2) {if(Isstringempty (str1) | | isstringempty (STR2) | |!str1.equals (STR2)) {            return false; }        return true; }}

4, hardening Singleton properties with private constructors

The first way:

 Public class elvis{         privatestaticfinalnew  Elvis ();          Private Elvis () {}           Public Static Elvis getinstance () {return  INSTANCE;}}

As previously stated, the private constructor makes the class non-instantiated, while the public static GetInstance method returns the Elvis member of the private static final, and this member is final guaranteed to be instantiated only once.

The second way:

 Public enum elvis{          INSTANCE;
public void leavethebuilding () {...}}

5. Avoid creating unnecessary objects

//creates lots of unnecessary duplicate objects-page 20-21  ImportJava.util.*;  Public classPerson {Private FinalDate birthDate;  PublicPerson (Date birthDate) {//defensive copy-see Item         This. birthDate =NewDate (Birthdate.gettime ()); }        //Other fields , methods omitted//DON ' T do this!      Public BooleanIsbabyboomer () {//unnecessary allocation of expensive objectCalendar gmtcal =calendar.getinstance (Timezone.gettimezone ("GMT")); Gmtcal.set (1946, Calendar.january, 1, 0, 0, 0); Date Boomstart=Gmtcal.gettime (); Gmtcal.set (1965, Calendar.january, 1, 0, 0, 0); Date Boomend=Gmtcal.gettime (); returnBirthdate.compareto (Boomstart) >= 0 &&Birthdate.compareto (boomend)< 0; }  }  

Improvements to:

 Public classperson{PrivateDate birthDate; Private Static FinalDate Boom_start; Private Static FinalDate Boom_end; Static{Calendar cal=calendar.getinstance (Timezone.gettimezone ("GMT")); //Baby Boom Start timeCal.set (1946, Calendar.january, 1, 0, 0, 0); Boom_start=Cal.gettime (); //Baby Boom End timeCal.set (1965, calendar.january, 1, 0, 0, 0); Boom_end=Cal.gettime (); }      //to determine whether a baby boomer is born     Public BooleanIsbabyboomer () {returnBirthdate.compareto (Boom_start) >= 0 && Birthdate.compareto (boom_end) < 0; }  }  

As you can see, the Isbabyboomer method of the first person class causes many objects to be created, improved using static blocks of code, and Boom_start and Boom_end are set to static methods. These two objects are created only once when the object is new.

6, elimination of expired object references

In general, programmers should be wary of memory leaks as long as the class is managing memory itself. Once the element is freed, any object references contained in the element should be emptied.

This article, or the need to combine specific application scenarios and examples to talk only meaningful. Later, I would like to add a similar question.

The example in the book feels silly, the pop method, the normal mind will release its references:

ImportJava.util.*;  Public classStack {Privateobject[] elements; Private intSize = 0; Private Static Final intDefault_initial_capacity = 16;  PublicStack () {Elements=NewObject[default_initial_capacity]; }         Public voidpush (Object e) {ensurecapacity (); Elements[size++] =e; }         PublicObject Pop () {if(Size = = 0)              Throw Newemptystackexception (); returnelements[--size]; }        /*** Ensure space for at least one more element, roughly * doubling the capacity each time the array needs to      Grow. */      Private voidensurecapacity () {if(Elements.length = =size) Elements= arrays.copyof (Elements, 2 * size + 1); }  }  

 Public Object Pop () {        if (size = =0             )thrownew  emptystackexception ( );         = elements[--size];         NULL ;       return result;    }  

Effective Java creating and destroying 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.