Tostringbuilder Study (a): Introduction to Common methods

Source: Internet
Author: User
Tags local time

first, Introduction and introduction
1, Tostringbuilder, Hashcodebuilder,Equalsbuilder, Tostringstyle,Reflectiontostringbuilder, Comparetobuilder, and so on are all under Commons-lang.jar, so use these classesBe sure to import Commons-lang.jar
2, why to useTostringbuilder?
The system usually prints the log, because the ToString () method of all entities uses a simple "+", because each "+" one will be a new string object, so if the system memory is small, it will burst memory (if the system entity is more).UseTostringbuilder can avoid this problem of burst memory.

second, sample learning
1.the Append method of Tostringbuilder
The Tostringbuilder class is primarily used for formatted output of classes. The Append method in Tostringbuilder can add basic types, arrays, and objects to the class, and only the added method will be output by ToString. Such as:
Class Taxreturn {
Private String SSN;
private int year;
Private String LastName;
Private BigDecimal Taxableincome;
Get/set method omitted
Public Taxreturn () {
}
Public Taxreturn (String pssn, int pyear, stringplastname, BigDecimal ptaxableincome) {
SETSSN (PSSN);
Setyear (pyear);
Setlastname (Plastname);
Settaxableincome (Ptaxableincome);
}
Public String toString () {
Return Newtostringbuilder (this). Append ("ssn", SSN). Append (' Year ', year). Append ("LastName",
LastName). toString ();

}

public int hashcode () {
returnnew Hashcodebuilder (3,7). Append (SSN). Append (year). Tohashcode ();
}

Public booleanequals (Object pobject) {
Booleanequals = false;
if (pobjectinstanceof Taxreturn) {
Taxreturn bean = (taxreturn) pobject;
equals = (new Equalsbuilder (). Append (ssn, BEAN.SSN). Append (Year,bean.year)). Isequals ();
}
Returnequals;
}

Public Intcompareto (Object pobject) {
ReturnComparetobuilder.reflectioncompare (this, pobject);
}

}

public class MainClass {

public static void Main (string[] PArgs) throwsexception {
Taxreturn return1 = new Taxreturn ("012-68-3242", 1998, "O ' Brien", New BigDecimal (43000.00));
Taxreturn return2 = new Taxreturn ("012-68-3242", 1999, "O ' Brien", New BigDecimal (45000.00));
Taxreturn return3 = new Taxreturn ("012-68-3242", 1999, "O ' Brien", New BigDecimal (53222.00));
System.out.println ("Tostringbuilder:" + return1.tostring ());
}
}
The results of the operation are as follows:
tostringbuilder:[email protected][ssn=012-68-3242,year=1998,lastname=o ' Brien]


2.The Reflectiontostring method of Tostringbuilder

The main method is to output the basic properties and values of the class. Such as:
public class MainClass {
publicstatic void Main (string[] args) {
MyClass one = new MyClass ("Becker", 35);
MyClass-n = new MyClass ("Becker", 35);
MyClass three = new MyClass ("Agassi", 33);

System.out.println ("one>>>" + one);
System.out.println ("two>>>" +);
System.out.println ("three>>>" + three);

System.out.println ("one equals" + one.equals ());
System.out.println ("one equals three" + one.equals (three));

System.out.println ("onehashcode>>>" +one.hashcode ());
System.out.println ("twohashcode>>>" +two.hashcode ());
System.out.println ("threehashcode>>>" +three.hashcode ());
}
}

Class MyClass {
Privatestring name = NULL;
Private intage = 0;

Publicmyclass (String name, int age) {
THIS.name = name;
This.age = age;
}

public boolean equals (Object obj) {
Return equalsbuilder.reflectionequals (this, obj);
}

Public stringtostring () {
Return tostringbuilder.reflectiontostring (this,
Tostringstyle.multi_line_style);

}

public int Hashcode () {
Return Hashcodebuilder.reflectionhashcode (this);
}
}
The results of the operation are as follows:

One>>>[email protected][
Name=becker
Age=35
]
Two>>>[email protected][
Name=becker
Age=35
]
Three>>>[email protected][
Name=agassi
Age=33
]
One equals? True
One equals three? False
One hashcode>>>462213092
hashcode>>>462213092
Three hashcode>>>-530629296

tostringstyle parameter Description:
1. Default_style
[Email protected] [Name=john Doe,age=33,smoker=false]
2. Multi_line_style
[Email protected] [
Name=john Doe
Age=33
Smoker=false
]
3. No_field_names_style
[Email protected] [Johndoe,33,false]
4. Short_prefix_style ( that is, the package name is cut off )
Person[name=john Doe,age=33,smoker=false]
5. Simple_style
John Doe,33,false

###############################################
Additional:
No matter what Java application you are developing, there are many tools/tool functions to write. You know, there are a lot of ready-made tool classes available, and the code quality is very good, without you to write, without you debugging, as long as you find.
In Apache Jakarta Common, Lang, the Java Toolkit, is the most widely used in all Apache Jakartacommon projects, and is useful to almost all of the more famous software you know, including Tomcat, Weblogic, Websphere, Eclipse, and so on. We'll start with this package to introduce the entire common project.

Lang in the tool class is more, here are a few main:
   classutils: Getshortclassname, this function should be in the Java.lang.Class class, I see a lot of people write this function themselves. Getallinterfaces,convertclassnamestoclasses,isassignable,primitivestowrappers,isinnerclass.
   numberutils: Class Stringtoint,todouble,createnumber,isallzeros for numeric and numeric and string conversions, int compare (FLOATLHS, float RHS), isnumber (String str ), Double min (double[]array).
   randomutils: Used to generate a random number.
   dateformatutils: Date time format conversion, and local time and UTC time conversion.
   dateutils:Date Tool class. Issameday,truncate,round,modify.

Several classes based on the reflection mechanism:
   Comparetobuilder:Comparisons, used in algorithms, sorting, Comparison places. Reflectioncompare,append.
   Equalsbuilder:Compared by reflection mechanism. Reflectionequals is used in many projects.
   hashcodebuilder:It is possible to generate hash code by reflection, where many algorithms involve hash code, but not everyone knows how to generate a hash code.
   Tostringbuilder: You can use this function when you need to overload the ToString function without writing code to list all the member information for the current class.

   I use a few other classes:
   serializationutilsSerialization in Java is a bit of a mystery and error prone.
   systemutilsYou can read some tool classes about JDK information, operating system information.

Tostringbuilder Study (a): Introduction to Common methods

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.