10th: Always overwrite ToString
This is nothing to say, which means that the default ToString method prints out the class name [email protected]+ hexadecimal hash code value. We should cover it so that it can show some more detailed and clear information.
11th: Carefully overwrite clone
Sometimes there is a scenario where you need to back up some data, and when you make a change to it, the other one will not be affected. In this way, direct foo a = new foo (); Foo B = A; is not feasible, B references and a point to the same object.
This article tells a lot, the final summary is, cloneable the interface pit Many, therefore best not to use.
The reason for the pit, of course, is that when a class contains a property of a reference type, it is cloned as a reference if it is not processed at the time of cloning. Therefore, if you only include the base type, you can use it. Typical usage is as follows
Public Final classPhoneNumberImplementscloneable {Private Final ShortAreaCode; Private Final Shortprefix; Private Final Shortlinenumber; PublicPhoneNumber (intAreaCode,intPrefixintlinenumber) {Rangecheck (AreaCode,999, "area code"); Rangecheck (prefix,999, "prefix"); Rangecheck (linenumber,9999, "line number"); This. AreaCode = ( Short) AreaCode; This. prefix = ( Short) prefix; This. linenumber = ( Short) linenumber; } Private Static voidRangecheck (intArgintMax, String name) { if(Arg < 0 | | arg >max)Throw NewIllegalArgumentException (name + ":" +Arg); } @Override Public Booleanequals (Object o) {if(O = = This) return true; if(! (OinstanceofPhoneNumber)) return false; PhoneNumber PN=(PhoneNumber) o; returnPn.linenumber = = LineNumber && Pn.prefix = =prefix&& Pn.areacode = =AreaCode; } @Override Public inthashcode () {intresult = 17; Result= * result +AreaCode; Result= * result +prefix; Result= * result +linenumber; returnresult; } @Override PublicString toString () {returnString.Format ("(%03d)%03d-%04d", AreaCode, prefix, linenumber); } @Override PublicPhoneNumber Clone () {Try { return(PhoneNumber)Super. Clone (); } Catch(clonenotsupportedexception e) {Throw NewAssertionerror ();//Can ' t happen } } Public Static voidMain (string[] args) {PhoneNumber pn=NewPhoneNumber (707, 867, 5309); Map<phonenumber, string> m =NewHashmap<phonenumber, string>(); M.put (PN,"Jenny"); System.out.println (M.get (Pn.clone ())); }}
View Code
is to implement the Cloneable interface, and then overwrite the Clone method in the object class. First call Super.clone, then strongly turn to the current class, and then make some corrections. For example, arrays, references.
At this point, the clone of the array is also extended.
The first method, then declares an array, iterates through the original array, and fills in the new array (the very low).
The second method, call the array's Clone method.
The third method (recommended), arrays.copyof (original array, new length);
Effective JAVA2 Reading notes-a common method for all objects (ii)